<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><div id="myscoll"></div><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>RabbitMQ | XiaoFei🥝</title><meta name="keywords" content="RabbitMQ"><meta name="author" content="XiaoFei🥝"><meta name="copyright" content="XiaoFei🥝"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="RabbitMQ">
<meta property="og:type" content="article">
<meta property="og:title" content="RabbitMQ">
<meta property="og:url" content="https://www.naste.top:1024/posts/3041119952.html">
<meta property="og:site_name" content="XiaoFei🥝">
<meta property="og:description" content="RabbitMQ">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://www.naste.top:9000/webp/1678672812.webp">
<meta property="article:published_time" content="2023-05-21T10:36:36.000Z">
<meta property="article:modified_time" content="2024-04-26T09:52:18.933Z">
<meta property="article:author" content="XiaoFei🥝">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="SpringBoot">
<meta property="article:tag" content="RabbitMQ">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://www.naste.top:9000/webp/1678672812.webp"><link rel="shortcut icon" href="/"><link rel="canonical" href="https://www.naste.top:1024/posts/3041119952"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/6.0.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.json","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":230},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.js',
      css: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'RabbitMQ',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-04-26 17:52:18'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://cdn1.tianli0.top/npm/element-ui@2.15.6/packages/theme-chalk/lib/index.css"><style id="themeColor"></style><style id="rightSide"></style><style id="transPercent"></style><style id="blurNum"></style><style id="settingStyle"></style><span id="fps"></span><style id="defineBg"></style><style id="menu_shadow"></style><svg aria-hidden="true" style="position:absolute; overflow:hidden; width:0; height:0"><symbol id="icon-sun" viewBox="0 0 1024 1024"><path d="M960 512l-128 128v192h-192l-128 128-128-128H192v-192l-128-128 128-128V192h192l128-128 128 128h192v192z" fill="#FFD878" p-id="8420"></path><path d="M736 512a224 224 0 1 0-448 0 224 224 0 1 0 448 0z" fill="#FFE4A9" p-id="8421"></path><path d="M512 109.248L626.752 224H800v173.248L914.752 512 800 626.752V800h-173.248L512 914.752 397.248 800H224v-173.248L109.248 512 224 397.248V224h173.248L512 109.248M512 64l-128 128H192v192l-128 128 128 128v192h192l128 128 128-128h192v-192l128-128-128-128V192h-192l-128-128z" fill="#4D5152" p-id="8422"></path><path d="M512 320c105.888 0 192 86.112 192 192s-86.112 192-192 192-192-86.112-192-192 86.112-192 192-192m0-32a224 224 0 1 0 0 448 224 224 0 0 0 0-448z" fill="#4D5152" p-id="8423"></path></symbol><symbol id="icon-moon" viewBox="0 0 1024 1024"><path d="M611.370667 167.082667a445.013333 445.013333 0 0 1-38.4 161.834666 477.824 477.824 0 0 1-244.736 244.394667 445.141333 445.141333 0 0 1-161.109334 38.058667 85.077333 85.077333 0 0 0-65.066666 135.722666A462.08 462.08 0 1 0 747.093333 102.058667a85.077333 85.077333 0 0 0-135.722666 65.024z" fill="#FFB531" p-id="11345"></path><path d="M329.728 274.133333l35.157333-35.157333a21.333333 21.333333 0 1 0-30.165333-30.165333l-35.157333 35.157333-35.114667-35.157333a21.333333 21.333333 0 0 0-30.165333 30.165333l35.114666 35.157333-35.114666 35.157334a21.333333 21.333333 0 1 0 30.165333 30.165333l35.114667-35.157333 35.157333 35.157333a21.333333 21.333333 0 1 0 30.165333-30.165333z" fill="#030835" p-id="11346"></path></symbol></svg><!-- hexo injector head_end start --><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/carousel-touch.js"></script><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.css" media="print" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="XiaoFei🥝" type="application/atom+xml">
</head><body><div id="loading-box" onclick="document.getElementById(&quot;loading-box&quot;).classList.add(&quot;loaded&quot;)"><div class="loading-bg"><div class="loading-img"></div><div class="loading-image-dot"></div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" onerror="onerror=null;src='/assets/r1.jpg'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">149</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">99</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">46</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">XiaoFei🥝</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div><center id="name-container"><a id="page-name" href="javascript:scrollToTop()">PAGE_NAME</a></center><div id="nav-right"><div id="search-button"><a class="search faa-parent animated-hover" title="检索站内任何你想要的信息"><svg class="faa-tada icon" style="height:24px;width:24px;fill:currentColor;position:relative;top:6px" aria-hidden="true"><use xlink:href="#icon-valentine_-search-love-find-heart"></use></svg><span> 搜索</span></a></div><a class="meihua faa-parent animated-hover" onclick="toggleWinbox()" title="美化设置-自定义你的风格" id="meihua-button"><svg class="faa-tada icon" style="height:26px;width:26px;fill:currentColor;position:relative;top:8px" aria-hidden="true"><use xlink:href="#icon-tupian1"></use></svg></a><a class="sun_moon faa-parent animated-hover" onclick="switchNightMode()" title="浅色和深色模式转换" id="nightmode-button"><svg class="faa-tada" style="height:25px;width:25px;fill:currentColor;position:relative;top:7px" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon">       </use></svg></a><div id="toggle-menu"><a><i class="fas fa-bars fa-fw"></i></a></div></div></div></nav><div id="post-info"><h1 class="post-title">RabbitMQ</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><svg class="meta_icon post-meta-icon" style="width:30px;height:30px;position:relative;top:10px"><use xlink:href="#icon-rili"></use></svg><span class="post-meta-label">发表于 </span><time class="post-meta-date-created" datetime="2023-05-21T10:36:36.000Z" title="发表于 2023-05-21 18:36:36">2023-05-21</time><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-gengxin1"></use></svg><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-04-26T09:52:18.933Z" title="更新于 2024-04-26 17:52:18">2024-04-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/">中间件</a><i class="fas fa-angle-right post-meta-separator"></i><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/%E6%B6%88%E6%81%AF%E4%B8%AD%E9%97%B4%E4%BB%B6/">消息中间件</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:8px"><use xlink:href="#icon-charuword"></use></svg><span class="post-meta-label">字数总计:</span><span class="word-count">2.4w</span><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:20px;height:20px;position:relative;top:5px"><use xlink:href="#icon-shizhong"></use></svg><span class="post-meta-label">阅读时长:</span><span>88分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="RabbitMQ"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:5px"><use xlink:href="#icon-eye"></use></svg><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><section class="main-hero-waves-area waves-area"><svg class="waves-svg" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto"><defs><path id="gentle-wave" d="M -160 44 c 30 0 58 -18 88 -18 s 58 18 88 18 s 58 -18 88 -18 s 58 18 88 18 v 44 h -352 Z"></path></defs><g class="parallax"><use href="#gentle-wave" x="48" y="0"></use><use href="#gentle-wave" x="48" y="3"></use><use href="#gentle-wave" x="48" y="5"></use><use href="#gentle-wave" x="48" y="7"></use></g></svg></section></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="目录"><a href="#目录" class="headerlink" title="目录"></a>目录</h1><p>[toc]</p>
<h1 id="必读"><a href="#必读" class="headerlink" title="必读"></a>必读</h1><blockquote>
<p><strong>本文档RabbitMQ版本：3.8.8</strong></p>
<p><strong>编程语言：Java</strong></p>
<p><strong>参考文档：<a target="_blank" rel="noopener" href="https://frxcat.fun/pages/e645d9/">https://frxcat.fun/pages/e645d9/</a></strong></p>
<p><strong>参考视频：<a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1cb4y1o7zz/">https://www.bilibili.com/video/BV1cb4y1o7zz/</a></strong></p>
</blockquote>
<h1 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h1><h2 id="Docker安装"><a href="#Docker安装" class="headerlink" title="Docker安装"></a>Docker安装</h2><h3 id="单机部署"><a href="#单机部署" class="headerlink" title="单机部署"></a>单机部署</h3><blockquote>
<p><strong>使用docker单机部署的RabbitMQ，用户名和密码默认都为<code>guest</code>，web访问地址为<code>ip+15672</code></strong></p>
</blockquote>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker run -d --restart=always --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.8.8-management</span><br></pre></td></tr></table></figure>
<h1 id="MQ概念"><a href="#MQ概念" class="headerlink" title="MQ概念"></a>MQ概念</h1><h2 id="什么是MQ"><a href="#什么是MQ" class="headerlink" title="什么是MQ"></a>什么是MQ</h2><p>MQ( 消息队列 message queue )，从字面意思上看，本质是个队列，FIFO 先进的数据先出 ，后进的数据后出，只不过队列中存放的内容是message 而已，还是</p>
<p>一种跨进程的通信机制，用于上下游传递消息。在互联网架构中，MQ 是一种非常常见的上下游<code>逻辑解耦 + 物理解耦</code>的消息通信服务。使用了 MQ 之后，消息发</p>
<p>送上游只需要依赖 MQ，不用依赖其他服务。 </p>
<h2 id="为什么要用MQ"><a href="#为什么要用MQ" class="headerlink" title="为什么要用MQ"></a>为什么要用MQ</h2><ol>
<li><p>流量消峰</p>
<p> 举个例子，如果订单系统最多能处理一万次订单，这个处理能力应付正常时段的下单时绰绰有余，正常时段我们下单一秒后就能返回结果。但是在高峰期，如果有两万次下单操作系统是处理不了的，只能限制订单超过一万后不允许用户下单。使用消息队列做缓冲，我们可以取消这个限制，把一秒内下的订单分 散成一段时间来处理，这时有些用户可能在下单十几秒后才能收到下单成功的操作，但是比不能下单的体验要好。</p>
</li>
<li><p>应用解耦</p>
<p> 以电商应用为例，应用中有订单系统、库存系统、物流系统、支付系统。用户创建订单后，如果耦合调用库存系统、物流系统、支付系统，任何一个子系统出了故障，都会造成下单操作异常。当转变成基于消息队列的方式后，系统间调用的问题会减少很多，比如物流系统因为发生故障，需要几分钟来修复。在这几分钟的时间里，物流系统要处理的内存被缓存在消息队列中，用户的下单操作可以正常完成。当物流系统恢复后，继续处理订单信息即可，中单用户感受不到物流系统的故障，提升系统的可用性。</p>
<p> <img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230524101404096.png" alt="image-20230524101404096"></p>
</li>
<li><p>异步处理</p>
<p> 有些服务间调用是异步的，例如 A 调用 B，B需要花费很长时间执行，但是 A 需要知道 B 什么时候可 以执行完，以前一般有两种方式，A过一段时间去调用 B 的查询 api 查询。或者 A 提供一个 callback api， B 执行完之后调用 api 通知 A 服务。这两种方式都不是很优雅，使用消息总线，可以很方便解决这个问题， A 调用 B 服务后，只需要监听 B 处理完成的消息，当 B 处理完成后，会发送一条消息给MQ，MQ会将此 消息转发给 A 服务。这样 A 服务既不用循环调用 B 的查询 api，也不用提供 callback api。同样 B 服务也不<br> 用做这些操作。A服务还能及时的得到异步处理成功的消息。</p>
<p> <img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230524101758274.png" alt="image-20230524101758274"></p>
</li>
</ol>
<h2 id="MQ分类"><a href="#MQ分类" class="headerlink" title="MQ分类"></a>MQ分类</h2><ul>
<li><p><strong>ActiveMQ</strong></p>
<p>  优点：单机吞吐量万级，时效性 ms 级，可用性高，基于主从架构实现高可用性，消息可靠性较 低的概率丢失数据</p>
<p>  缺点：官方社区现在对 ActiveMQ 5.x 维护越来越少，高吞吐量场景较少使用</p>
</li>
<li><p><strong>Kafka</strong></p>
<p>  大数据的杀手锏，谈到大数据领域内的消息传输，则绕不开 Kafka，这款为大数据而生的消息中间件，以其百万级 TPS 的吞吐量名声大噪，迅速成为大数据领域的宠儿，在数据采集、传输、存储的过程中发挥着举足轻重的作用。目前已经被 LinkedIn，Uber，Twitter，Netflix 等大公司所采纳。</p>
<p>  优点: 性能卓越，单机写入 TPS 约在百万条/秒，最大的优点，就是吞吐量高。时效性 ms 级可用性非常高，kafka 是分布式的，一个数据多个副本，少数机器宕机，不会丢失数据，不会导致不可用,消费者采用 Pull 方式获取消息，消息有序，通过控制能够保证所有消息被消费且仅被消费一次；有优秀的第三方Kafka Web 管理界面 Kafka-Manager；在日志领域比较成熟，被多家公司和多个开源项目使用；功能支持：功能 较为简单，主要支持简单的 MQ 功能，在大数据领域的实时计算以及日志采集被大规模使用</p>
<p>  缺点：Kafka 单机超过 64 个队列/分区，Load 会发生明显的飙高现象，队列越多，load 越高，发送消息响应时间变长，使用短轮询方式，实时性取决于轮询间隔时间，消费失败不支持重试；支持消息顺序，但是一台代理宕机后，就会产生消息乱序，社区更新较慢</p>
</li>
<li><p><strong>RocketMQ</strong></p>
<p>  RocketMQ 出自阿里巴巴的开源产品，用 Java 语言实现，在设计时参考了 Kafka，并做出了自己的一些改进。被阿里巴巴广泛应用在订单，交易，充值，流计算，消息推送，日志流式处理，binglog 分发等场景。</p>
<p>  优点：单机吞吐量十万级，可用性非常高，分布式架构,消息可以做到 0 丢失,MQ 功能较为完善，还是分布式的，扩展性好,支持 10 亿级别的消息堆积，不会因为堆积导致性能下降，源码是 java 我们可以自己阅读源码，定制自己公司的 MQ</p>
<p>  缺点：支持的客户端语言不多，目前是 java 及 c++，其中 c++ 不成熟；社区活跃度一般,没有在 MQ 核心中去实现 JMS 等接口,有些系统要迁移需要修改大量代码</p>
</li>
<li><p><strong>RabbitMQ</strong></p>
<p>  2007 年发布，是一个在AMQP(高级消息队列协议)基础上完成的，可复用的企业消息系统，是当前最主流的消息中间件之一。</p>
<p>  优点：由于 erlang 语言的高并发特性，性能较好；吞吐量到万级，MQ 功能比较完备,健壮、稳定、易用、跨平台、支持多种语言 如：Python、Ruby、.NET、Java、JMS、C、PHP、ActionScript、XMPP、STOMP 等，支持 AJAX 文档齐全；开源提供的管理界面非常棒，用起来很好用,社区活跃度高；更新频率相当高</p>
<p>  缺点：商业版需要收费,学习成本较高</p>
</li>
</ul>
<h2 id="MQ选择"><a href="#MQ选择" class="headerlink" title="MQ选择"></a>MQ选择</h2><ul>
<li><p><strong>Kafka</strong></p>
<p>  Kafka 主要特点是基于 Pull 的模式来处理消息消费，追求高吞吐量，一开始的目的就是用于日志收集和传输，适合产生大量数据的互联网服务的数据收集业务。大型公司建议可以选用，如果有日志采集功能，肯定是首选 kafka 了</p>
</li>
<li><p><strong>RocketMQ</strong></p>
<p>  天生为金融互联网领域而生，对于可靠性要求很高的场景，尤其是电商里面的订单扣款，以及业务削峰，在大量交易涌入时，后端可能无法及时处理的情况。RoketMQ 在稳定性上可能更值得信赖，这些业务场景在阿里双 11 已经经历了多次考验，如果你的业务有上述并发场景，建议可以选择 RocketMQ</p>
</li>
<li><p><strong>RabbitMQ</strong></p>
<p>  结合 erlang 语言本身的并发优势，性能好时效性微秒级，社区活跃度也比较高，管理界面用起来十分 方便，如果你的数据量没有那么大，中小型公司优先选择功能比较完备的 RabbitMQ</p>
</li>
</ul>
<h1 id="RabbitMQ相关概念"><a href="#RabbitMQ相关概念" class="headerlink" title="RabbitMQ相关概念"></a>RabbitMQ相关概念</h1><h2 id="RabbitMQ概念"><a href="#RabbitMQ概念" class="headerlink" title="RabbitMQ概念"></a>RabbitMQ概念</h2><p>RabbitMQ 是一个消息中间件：它接受并转发消息。你可以把它当做一个快递站点，当你要发送一个包裹时，你把你的包裹放到快递站，快递员最终会把你的快递送到收件人那里，按照这种逻辑 RabbitMQ 是 一个快递站，一个快递员帮你传递快件。RabbitMQ 与快递站的主要区别在于，它不处理快件而是接收，存储和转发消息数据。</p>
<h2 id="RabbitMQ四大核心概念"><a href="#RabbitMQ四大核心概念" class="headerlink" title="RabbitMQ四大核心概念"></a>RabbitMQ四大核心概念</h2><ul>
<li><p><code>生产者</code>：</p>
<p>  产生数据发送消息的程序</p>
</li>
<li><p><code>交换机</code>：</p>
<p>  是 RabbitMQ 非常重要的一个部件，一方面它接收来自生产者的消息，另一方面它将消息 推送到队列中。交换机必须确切知道如何处理它接收到的消息，是将这些消息推送到特定队列还是推送到多个队列，亦或者是把消息丢弃，这个得有交换机类型决定</p>
</li>
<li><p><code>队列</code>：</p>
<p>  是 RabbitMQ 内部使用的一种数据结构，尽管消息流经 RabbitMQ 和应用程序，但它们只能存储在队列中。队列仅受主机的内存和磁盘限制的约束，本质上是一个大的消息缓冲区。许多生产者可以将消息发送到一个队列，许多消费者可以尝试从一个队列接收数据。这就是我们使用队列的方式</p>
</li>
<li><p><code>消费者</code>：</p>
<p>  消费与接收具有相似的含义。消费者大多时候是一个等待接收消息的程序。请注意生产者，消费者和消息中间件很多时候并不在同一机器上。同一个应用程序既可以是生产者又是可以是消费者。</p>
</li>
</ul>
<h2 id="RabbitMQ核心部分"><a href="#RabbitMQ核心部分" class="headerlink" title="RabbitMQ核心部分"></a>RabbitMQ核心部分</h2><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/202305241050001.png" alt="202305241050001"></p>
<h2 id="RabbitMQ名词介绍"><a href="#RabbitMQ名词介绍" class="headerlink" title="RabbitMQ名词介绍"></a>RabbitMQ名词介绍</h2><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230524110356724.png" alt="image-20230524110356724"></p>
<ul>
<li><code>Producer</code>：消息生产者。</li>
<li><code>Consumer</code>：消息消费者。</li>
<li><code>Broker</code>：接收和分发消息的应用，RabbitMQ Server 就是 Message Broker</li>
<li><code>Virtual host</code>：出于多租户和安全因素设计的，把 AMQP 的基本组件划分到一个虚拟的分组中，类似于网络中的 namespace 概念。当多个不同的用户使用同一个 RabbitMQ server 提供的服务时，可以划分出多个vhost，每个用户在自己的 vhost 创建 exchange／queue 等</li>
<li><code>Connection</code>：publisher／consumer 和 broker 之间的 TCP 连接到 RabbitMQ Server</li>
<li><code>Channel</code>：如果每一次访问 RabbitMQ 都建立一个 Connection，在消息量大的时候建立 TCP Connection 的开销将是巨大的，效率也较低。Channel 是在 connection 内部建立的逻辑连接，如果应用程序支持多线程，通常每个 thread 创建单独的 channel 进行通讯，AMQP method 包含了 channel id 帮助客 户端和 message broker 识别 channel，所以 channel 之间是完全隔离的。Channel 作为轻量级的 Connection 极大减少了操作系统建立 TCP connection 的开销</li>
<li><code>Exchange</code>：message 到达 broker 的第一站，根据分发规则，匹配查询表中的 routing key，分发 消息到 queue 中去。常用的类型有：direct (point-to-point)，topic (publish-subscribe) and fanout (multicast)</li>
<li><p><code>Queue</code>：消息最终被送到这里等待 consumer 取走</p>
</li>
<li><p><code>Binding</code>：exchange 和 queue 之间的虚拟连接，binding 中可以包含 routing key，Binding 信息被保 存到 exchange 中的查询表中，用于 message 的分发依据</p>
</li>
<li><code>Routing Key（路由键）</code>：消息发送给 Exchange（交换器）时，消息将拥有一个路由键（默认为空）， Exchange（交换器）根据这个路由键将消息发送到匹配的队列中</li>
<li><code>Binding Key（绑定键）</code>：指定当前 Exchange（交换器）下，什么样的 Routing Key（路由键）会被下派到当前绑定的 Queue 中</li>
<li><code>Direct</code>：完全匹配，消息路由到那些 Routing Key 与 Binding Key 完全匹配的 Queue 中。比如 Routing Key 为<code>cleint-key</code>，只会转发<code>cleint-key</code>，不会转发<code>cleint-key.1</code>，也不会转发<code>cleint-key.1.2</code></li>
<li>Topic：模式匹配，Exchange 会把消息发送到一个或者多个满足通配符规则的 routing-key 的 Queue。其中<em>表号匹配一个 word，#匹配多个 word 和路径，路径之间通过.隔开。如满足a.</em>.c的 routing-key 有a.hello.c；满足#.hello的 routing-key 有a.b.c.helo</li>
<li><code>Fanout</code>：忽略匹配，把所有发送到该 Exchange 的消息路由到所有与它绑定 的Queue 中</li>
</ul>
<h1 id="代码工具类"><a href="#代码工具类" class="headerlink" title="代码工具类"></a>代码工具类</h1><h2 id="RabbitMQ连接信道工具类"><a href="#RabbitMQ连接信道工具类" class="headerlink" title="RabbitMQ连接信道工具类"></a>RabbitMQ连接信道工具类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 获取RabbitMQ连接信道工具类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ChannelUtils</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">HOST</span> <span class="operator">=</span> <span class="string">&quot;192.168.40.168&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">USERNAME</span> <span class="operator">=</span> <span class="string">&quot;guest&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">PASSWORD</span> <span class="operator">=</span> <span class="string">&quot;guest&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取RabbitMQ连接信道</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Channel <span class="title function_">getChannel</span><span class="params">()</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">//创建一个连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//工厂IP 连接RabbitMQ对列</span></span><br><span class="line">        factory.setHost(HOST);</span><br><span class="line">        <span class="comment">//用户名</span></span><br><span class="line">        factory.setUsername(USERNAME);</span><br><span class="line">        <span class="comment">//密码</span></span><br><span class="line">        factory.setPassword(PASSWORD);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建连接</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="keyword">return</span> connection.createChannel();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="睡眠工具类"><a href="#睡眠工具类" class="headerlink" title="睡眠工具类"></a>睡眠工具类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 睡眠工具类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SleepUtils</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">sleep</span><span class="params">(<span class="type">int</span> second)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000L</span> * second);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            Thread.currentThread().interrupt();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="入门案例"><a href="#入门案例" class="headerlink" title="入门案例"></a>入门案例</h1><h2 id="Hello-World"><a href="#Hello-World" class="headerlink" title="Hello World"></a>Hello World</h2><p>用 Java 编写两个程序。单个生产者和消费者</p>
<p>在下图中，“ P” 是生产者，“ C” 是消费者。中间的框是一个队列， RabbitMQ 代表使用者保留的消息缓冲区</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230524145429005.png" alt="image-20230524145429005"></p>
<h3 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h3><h4 id="maven依赖"><a href="#maven依赖" class="headerlink" title="maven依赖"></a>maven依赖</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--rabbitmq 依赖客户端--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.rabbitmq<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>amqp-client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.8.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--操作文件流的一个依赖--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="生产者"><a href="#生产者" class="headerlink" title="生产者"></a>生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 生产者代码</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerOne</span> &#123;</span><br><span class="line">    <span class="comment">//对列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;hello&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//发消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//需要发送的消息</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;Hello,world&quot;</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 发送一个消息</span></span><br><span class="line"><span class="comment">         * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">         * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">         * 3.其他参数信息</span></span><br><span class="line"><span class="comment">         * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">        </span><br><span class="line">        System.out.println(<span class="string">&quot;消息发送完毕&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="消费者"><a href="#消费者" class="headerlink" title="消费者"></a>消费者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消费者</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerOne</span> &#123;</span><br><span class="line">    <span class="comment">//队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;hello&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//接收消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">//获取连接信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//推送的消息如何进行消费的接口回调，在该接口中进行消息消费</span></span><br><span class="line">        <span class="comment">//TODO 这里由于DeliverCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag, message) -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;接收消息了&quot;</span>);</span><br><span class="line">            System.out.println(<span class="keyword">new</span> <span class="title class_">String</span>(message.getBody()));</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//取消消费的一个回调接口 如在消费的时候队列被删除掉了</span></span><br><span class="line">        <span class="comment">//TODO 这里由于CancelCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">CancelCallback</span> <span class="variable">cancelCallback</span> <span class="operator">=</span> consumerTag -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;消息消费被中断&quot;</span>);</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 消费者消费消息</span></span><br><span class="line"><span class="comment">         * 1.消费哪个队列</span></span><br><span class="line"><span class="comment">         * 2.消费成功之后是否要自动应答true：代表自动应答false:代表手动应答</span></span><br><span class="line"><span class="comment">         * 3.消费者未成功消费的回调</span></span><br><span class="line"><span class="comment">         * 4.消费者取消消费的回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="literal">true</span>, deliverCallback, cancelCallback);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Work-Queues"><a href="#Work-Queues" class="headerlink" title="Work Queues"></a>Work Queues</h2><p>Work Queues 是工作队列（又称任务队列）的主要思想是避免立即执行资源密集型任务，而不得不等待它完成。相反我们安排任务在之后执行。我们把任务封装为消息并将其发送到队列。在后台运行的工作进程将弹出任务并最终执行作业。当有多个工作线程时，这些工作线程将一起处理这些任务。<strong><code>相当于负载均衡，hello world是一个队列一个工作现场，work queues是多个消费者同时对消息进行消费</code></strong></p>
<h3 id="轮询消费"><a href="#轮询消费" class="headerlink" title="轮询消费"></a>轮询消费</h3><blockquote>
<p><strong>代码还是前面<code>Hello World</code>中的生产者和消费者代码，只是使用了idea启动了两个消费者</strong></p>
</blockquote>
<p>轮询消费消息指的是轮流消费消息，即每个工作队列都会获取一个消息进行消费，并且获取的次数按照顺序依次往下轮流。</p>
<p>案例中生产者叫做 Task，一个消费者就是一个工作队列，启动两个工作队列消费消息，这个两个工作队列会以轮询的方式消费消息。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230524160903040.png" alt="image-20230524160903040"></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230524160935245.png" alt="image-20230524160935245"></p>
<h2 id="web页面添加队列"><a href="#web页面添加队列" class="headerlink" title="web页面添加队列"></a>web页面添加队列</h2><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230524164535093.png" alt="image-20230524164535093"></p>
<ol>
<li>点击 <code>Queues</code> 菜单</li>
<li>点击 <code>Add a new queue</code>，弹出下拉菜单</li>
<li>下方的很多参数可以进行选择（旁边有 ？的参数），如优先级（<code>Lazy mode</code>）、绑定死信队列（<code>Dead letter exchange/routing key</code>）</li>
<li>执行步骤 3 后，在 <code>Arguments</code> 的第一个文本框弹出对应的参数，类似于 Map 的 key</li>
<li>第二个文本框填写参数，类似于 Map 的 value</li>
<li>第三个是下拉菜单，选择 value 类型</li>
<li>点击 <code>Add queue</code>，添加队列</li>
</ol>
<p>旁边有 ？的参数，就是 <code>channel.queueDeclare(队列名/String, 持久化/boolean, 共享消费/boolean, 自动删除/boolean, 配置参数/Map);</code> 或者 <code>channel.basicPublish(交换机名/String, 队列名/String, 配置参数/Map, 消息/String);</code> 的参数：配置参数/Map 的 key</p>
<h1 id="消息应答和发布"><a href="#消息应答和发布" class="headerlink" title="消息应答和发布"></a>消息应答和发布</h1><h2 id="消息应答"><a href="#消息应答" class="headerlink" title="消息应答"></a>消息应答</h2><h3 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h3><p>消费者完成一个任务可能需要一段时间，如果其中一个消费者处理一个长的任务并仅只完成了部分突然它挂掉了，会发生什么情况。RabbitMQ 一旦向消费者传递了一条消息，便立即将该消息标记为删除。在这种情况下，突然有个消费者挂掉了，我们将丢失正在处理的消息。以及后续发送给该消费者的消息，因为它无法接收到。</p>
<p>为了保证消息在发送过程中不丢失，引入消息应答机制，消息应答就是：<mark><strong>消费者在接收到消息并且处理该消息之后，告诉 RabbitMQ 它已经处理了，RabbitMQ 可以把该消息删除了</strong></mark>。</p>
<h3 id="自动应答（无需设置）"><a href="#自动应答（无需设置）" class="headerlink" title="自动应答（无需设置）"></a>自动应答（无需设置）</h3><p>消息发送后立即被认为已经传送成功，这种模式需要在<strong>高吞吐量和数据传输安全性方面做权衡</strong>,因为这种模式如果消息在接收到之前，消费者那边出现连接或者 channel 关闭，那么消息就丢失了,当然另一方面这种模式消费者那边可以传递过载的消息，<strong>没有对传递的消息数量进行限制</strong>，当然这样有可能使得消费者这边由于接收太多还来不及处理的消息，导致这些消息的积压，最终使得内存耗尽，最终这些消费者线程被操作系统杀死，<strong>所以这种模式仅适用在消费者可以高效并以 某种速率能够处理这些消息的情况下使用。</strong></p>
<h3 id="手动应答方法及参数解释"><a href="#手动应答方法及参数解释" class="headerlink" title="手动应答方法及参数解释"></a>手动应答方法及参数解释</h3><ul>
<li><code>Channel.basicAck</code> (肯定确认应答)：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">basicAck(<span class="type">long</span> deliveryTag, <span class="type">boolean</span> multiple);</span><br></pre></td></tr></table></figure>
<p>第一个参数是消息的标记，第二个参数表示是否应用于多消息，RabbitMQ 已知道该消息并且成功的处理消息，可以将其丢弃了</p>
<ul>
<li><code>Channel.basicReject</code> (否定确认应答)</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">basicReject(<span class="type">long</span> deliveryTag, <span class="type">boolean</span> requeue);</span><br></pre></td></tr></table></figure>
<p>第一个参数表示拒绝 <code>deliveryTag</code> 对应的消息，第二个参数表示是否 <code>requeue</code>：true 则重新入队列，false 则丢弃或者进入死信队列。</p>
<p>该方法 reject 后，该消费者还是会消费到该条被 reject 的消息。</p>
<ul>
<li><code>Channel.basicNack</code> (用于否定确认)：示己拒绝处理该消息，可以将其丢弃了</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">basicNack(<span class="type">long</span> deliveryTag, <span class="type">boolean</span> multiple, <span class="type">boolean</span> requeue);</span><br></pre></td></tr></table></figure>
<p>第一个参数表示拒绝 <code>deliveryTag</code> 对应的消息，第二个参数是表示否应用于多消息，第三个参数表示是否 <code>requeue</code>，与 basicReject 区别就是同时支持多个消息，可以 拒绝签收 该消费者先前接收未 ack 的所有消息。拒绝签收后的消息也会被自己消费到。</p>
<ul>
<li><code>Channel.basicRecover</code></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">basicRecover(<span class="type">boolean</span> requeue);</span><br></pre></td></tr></table></figure>
<p>是否恢复消息到队列，参数是是否 <code>requeue</code>，true 则重新入队列，并且尽可能的将之前 <code>recover</code> 的消息投递给其他消费者消费，而不是自己再次消费。false 则消息会重新被投递给自己。</p>
<p><strong>上面手动应答方法中Multiple参数的解释：</strong></p>
<ul>
<li><p>true：代表批量应答 channel 上未应答的消息。比如说 channel 上有传送 tag 的消息 5,6,7,8 当前 tag 是 8 那么此时 5-8 的这些还未应答的消息都会被确认收到消息应答</p>
</li>
<li><p>false：同上面相比只会应答 tag=8 的消息 5,6,7 这三个消息依然不会被确认收到消息应答</p>
</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230524210837312.png" alt="image-20230524210837312"></p>
<h3 id="消息自动重新入队"><a href="#消息自动重新入队" class="headerlink" title="消息自动重新入队"></a>消息自动重新入队</h3><p>如果消费者由于某些原因失去连接(其通道已关闭，连接已关闭或 TCP 连接丢失)，导致消息未发送 ACK 确认，RabbitMQ 将了解到消息未完全处理，并将对其重新排队。如果此时其他消费者可以处理，它将很快将其重新分发给另一个消费者。这样，即使某个消费者偶尔死亡，也可以确保不会丢失任何消息。</p>
<blockquote>
<p><strong>下面图片顺序，从左至右，从上至下看，是连续图，上下两张图（1，2），下面两张图（3，4）</strong></p>
</blockquote>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.4hplocbhsdk0.webp" alt="img"></p>
<h3 id="手动应答案例"><a href="#手动应答案例" class="headerlink" title="手动应答案例"></a>手动应答案例</h3><h4 id="生产者-1"><a href="#生产者-1" class="headerlink" title="生产者"></a>生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消息生产者</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerTwo</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TASK_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;ACK_QUEUE&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(TASK_QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//在控制台中输入需要生产的信息</span></span><br><span class="line">        <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">        System.out.println(<span class="string">&quot;请输入信息：&quot;</span>);</span><br><span class="line">        <span class="keyword">while</span> (scanner.hasNext()) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> scanner.next();</span><br><span class="line"></span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * 发送一个消息</span></span><br><span class="line"><span class="comment">             * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">             * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">             * 3.其他参数信息</span></span><br><span class="line"><span class="comment">             * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, TASK_QUEUE_NAME, <span class="literal">null</span>, message.getBytes(StandardCharsets.UTF_8));</span><br><span class="line"></span><br><span class="line">            System.out.println(<span class="string">&quot;生产者发出消息:&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="消费者-1"><a href="#消费者-1" class="headerlink" title="消费者"></a>消费者</h4><blockquote>
<p><strong>没有应答的消息会在<code>Unacked</code>中进行统计，等后续消费者对该消息进行消费</strong></p>
</blockquote>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230525100622070.png" alt="image-20230525100622070"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.CancelCallback;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.DeliverCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.SleepUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Channel.basicAck (肯定确认应答)实现手动消息应答</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerTwo</span> &#123;</span><br><span class="line">    <span class="comment">//队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TASK_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;ACK_QUEUE&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//接受消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        System.out.println(<span class="string">&quot;C1等待接受消息处理时间较短&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//推送的消息如何进行消费的接口回调，在该接口中进行消息消费</span></span><br><span class="line">        <span class="comment">//TODO 这里由于DeliverCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag, message) -&gt; &#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//沉睡1S</span></span><br><span class="line">            SleepUtils.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(<span class="string">&quot;接受到的消息:&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">            </span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * 手动应答</span></span><br><span class="line"><span class="comment">             * 1.消息的标记Tag</span></span><br><span class="line"><span class="comment">             * 2.是否批量应答 false表示不批量应答信道中的消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicAck(message.getEnvelope().getDeliveryTag(), <span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//取消消费的一个回调接口 如在消费的时候队列被删除掉了</span></span><br><span class="line">        <span class="comment">//TODO 这里由于CancelCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">CancelCallback</span> <span class="variable">cancelCallback</span> <span class="operator">=</span> (consumerTag -&gt; &#123;</span><br><span class="line">            System.out.println(consumerTag + <span class="string">&quot;消费者取消消费接口回调逻辑&quot;</span>);</span><br><span class="line"></span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置参数值为false，设置为手动应答，手动应答的代码在DeliverCallback消费接口中进行实现</span></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">autoAck</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 消费者消费消息</span></span><br><span class="line"><span class="comment">         * 1.消费哪个队列</span></span><br><span class="line"><span class="comment">         * 2.消费成功之后是否要自动应答true：代表自动应答false:代表手动应答</span></span><br><span class="line"><span class="comment">         * 3.消费者未成功消费的回调</span></span><br><span class="line"><span class="comment">         * 4.消费者取消消费的回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, cancelCallback);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="RabbitMQ持久化"><a href="#RabbitMQ持久化" class="headerlink" title="RabbitMQ持久化"></a>RabbitMQ持久化</h2><p>当 RabbitMQ 服务停掉以后，消息生产者发送过来的消息不丢失要如何保障？默认情况下 RabbitMQ 退出或由于某种原因崩溃时，它忽视队列和消息，除非告知它不要这样做。确保消息不会丢失需要做两件事：<strong>我们需要将队列和消息都标记为持久化。</strong></p>
<h3 id="队列持久化和消息持久化解释"><a href="#队列持久化和消息持久化解释" class="headerlink" title="队列持久化和消息持久化解释"></a>队列持久化和消息持久化解释</h3><ul>
<li>在 RabbitMQ 中，消息持久化和队列持久化是两个独立的概念，因此可以分别开启它们，不需要同时开启队列持久化来启用消息持久化。</li>
<li>在 RabbitMQ 中，消息持久化和队列持久化可以保证消息在 RabbitMQ 服务器发生故障时不会丢失，但它们并不会影响消息被消费后是否被删除的行为。当一个消费者从一个队列中获取一条消息并处理完成后，该消息默认情况下会被从队列中删除。这意味着，即使您开启了消息持久化和队列持久化，从队列中获取并处理的消息仍然会被删除，不会被保存在队列中。</li>
</ul>
<h3 id="队列持久化"><a href="#队列持久化" class="headerlink" title="队列持久化"></a>队列持久化</h3><p>之前创建的队列都是非持久化的，RabbitMQ 如果重启的化，该队列就会被删除掉，如果要队列实现持久化需要在声明队列的时候把 durable 参数设置为true，代表开启持久化</p>
<blockquote>
<p><strong>已经开启持久化的队列，会再<code>Features</code>中标注<code>D</code></strong></p>
</blockquote>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230525101558937.png" alt="image-20230525101558937"></p>
<h4 id="生产者-2"><a href="#生产者-2" class="headerlink" title="生产者"></a>生产者</h4><blockquote>
<p><strong>如果即将创建的队列在之前是非持久化创建的，必须要先将创建的非持久化队列进行删除，然后再创建新的持久化队列，再RabbitMQ的web控制台上进行删除</strong></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消息生产者，并且在创建队列的时候，进行队列持久化</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerTwo</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TASK_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;QUEUE_MESSAGE&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//开启持久化</span></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">durable</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(TASK_QUEUE_NAME, durable, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//在控制台中输入需要生产的信息</span></span><br><span class="line">        <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">        System.out.println(<span class="string">&quot;请输入信息：&quot;</span>);</span><br><span class="line">        <span class="keyword">while</span> (scanner.hasNext()) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> scanner.next();</span><br><span class="line"></span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * 发送一个消息</span></span><br><span class="line"><span class="comment">             * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">             * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">             * 3.其他参数信息</span></span><br><span class="line"><span class="comment">             * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, TASK_QUEUE_NAME, <span class="literal">null</span>, message.getBytes(StandardCharsets.UTF_8));</span><br><span class="line"></span><br><span class="line">            System.out.println(<span class="string">&quot;生产者发出消息:&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="消费者-2"><a href="#消费者-2" class="headerlink" title="消费者"></a>消费者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.CancelCallback;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.DeliverCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.SleepUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消费者代码</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerTwo</span> &#123;</span><br><span class="line">    <span class="comment">//队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TASK_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;QUEUE_MESSAGE&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//接受消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        System.out.println(<span class="string">&quot;C1等待接受消息处理时间较短&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//推送的消息如何进行消费的接口回调，在该接口中进行消息消费</span></span><br><span class="line">        <span class="comment">//TODO 这里由于DeliverCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag, message) -&gt; &#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//沉睡1S</span></span><br><span class="line">            SleepUtils.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(<span class="string">&quot;接受到的消息:&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">            <span class="comment">//手动应答</span></span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * 1.消息的标记Tag</span></span><br><span class="line"><span class="comment">             * 2.是否批量应答 false表示不批量应答信道中的消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicAck(message.getEnvelope().getDeliveryTag(), <span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//取消消费的一个回调接口 如在消费的时候队列被删除掉了</span></span><br><span class="line">        <span class="comment">//TODO 这里由于CancelCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">CancelCallback</span> <span class="variable">cancelCallback</span> <span class="operator">=</span> (consumerTag -&gt; &#123;</span><br><span class="line">            System.out.println(consumerTag + <span class="string">&quot;消费者取消消费接口回调逻辑&quot;</span>);</span><br><span class="line"></span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置参数值为false，设置为手动应答，手动应答的代码在DeliverCallback消费接口中进行实现</span></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">autoAck</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 消费者消费消息</span></span><br><span class="line"><span class="comment">         * 1.消费哪个队列</span></span><br><span class="line"><span class="comment">         * 2.消费成功之后是否要自动应答true：代表自动应答false:代表手动应答</span></span><br><span class="line"><span class="comment">         * 3.消费者未成功消费的回调</span></span><br><span class="line"><span class="comment">         * 4.消费者取消消费的回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, cancelCallback);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="消息持久化"><a href="#消息持久化" class="headerlink" title="消息持久化"></a>消息持久化</h3><h4 id="生产者-3"><a href="#生产者-3" class="headerlink" title="生产者"></a>生产者</h4><blockquote>
<p><strong>需要生产者发布消息的时候进行消息持久化</strong></p>
<p><strong>在 basicPublish 方法的第二个参数添加这个属性： <code>MessageProperties.PERSISTENT_TEXT_PLAIN</code></strong></p>
</blockquote>
<p>将消息标记为持久化并不能完全保证不会丢失消息。尽管它告诉 RabbitMQ 将消息保存到磁盘，但是这里依然存在当消息刚准备存储在磁盘的时候 但是还没有存储完，消息还在缓存的一个间隔点。此时并没 有真正写入磁盘。持久性保证并不强，但是对于我们的简单任务队列而言，这已经绰绰有余了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.MessageProperties;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消息生产者，并且再消息生产的时候，进行消息持久化</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerTwo</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TASK_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;QUEUE_MESSAGE&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(TASK_QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//在控制台中输入需要生产的信息</span></span><br><span class="line">        <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">        System.out.println(<span class="string">&quot;请输入信息：&quot;</span>);</span><br><span class="line">        <span class="keyword">while</span> (scanner.hasNext()) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> scanner.next();</span><br><span class="line"></span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * 发送一个消息</span></span><br><span class="line"><span class="comment">             * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">             * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">             * 3.其他参数信息，这使用【MessageProperties.PERSISTENT_TEXT_PLAIN】开启消息持久化</span></span><br><span class="line"><span class="comment">             * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));</span><br><span class="line"></span><br><span class="line">            System.out.println(<span class="string">&quot;生产者发出消息:&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="消费者-3"><a href="#消费者-3" class="headerlink" title="消费者"></a>消费者</h4><blockquote>
<p><strong>和队列持久化中的消费者代码一致</strong></p>
</blockquote>
<h2 id="不公平分发"><a href="#不公平分发" class="headerlink" title="不公平分发"></a>不公平分发</h2><blockquote>
<p><strong>原来多个消费者是采用轮询消费，一个消费者一个。但是可能由于每个消费者的处理消息的能力不同，所以手动干预每个消费者消费消息的能力，<code>处理消息快的消费者多消费消息，能者多劳</code></strong></p>
<p><strong>在消费者中消费消息之前，所有的消费者都要设置参数 <code>channel.basicQos(1);</code></strong></p>
<p><strong>不公平分发和预取值分发都用到 <code>basicQos</code> 方法，如果取值为 1，代表不公平分发，取值不为1，代表预取值分发</strong></p>
</blockquote>
<p>在最开始的时候我们学习到 RabbitMQ 分发消息采用的轮询分发，但是在某种场景下这种策略并不是很好，比方说有两个消费者在处理任务，其中有个<strong>消费者 1</strong> 处理任务的速度非常快，而另外一个<strong>消费者 2</strong> 处理速度却很慢，这个时候我们还是采用轮询分发的化就会到这处理速度快的这个消费者很大一部分时间处于空闲状态，而处理慢的那个消费者一直在干活，这种分配方式在这种情况下其实就不太好，但是 RabbitMQ 并不知道这种情况它依然很公平的进行分发。</p>
<h3 id="生产者-4"><a href="#生产者-4" class="headerlink" title="生产者"></a>生产者</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.MessageProperties;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消息生产者</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerTwo</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TASK_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;QUEUE_MESSAGE&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(TASK_QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//在控制台中输入需要生产的信息</span></span><br><span class="line">        <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">        System.out.println(<span class="string">&quot;请输入信息：&quot;</span>);</span><br><span class="line">        <span class="keyword">while</span> (scanner.hasNext()) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> scanner.next();</span><br><span class="line"></span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * 发送一个消息</span></span><br><span class="line"><span class="comment">             * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">             * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">             * 3.其他参数信息，这使用【MessageProperties.PERSISTENT_TEXT_PLAIN】开启消息持久化</span></span><br><span class="line"><span class="comment">             * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));</span><br><span class="line"></span><br><span class="line">            System.out.println(<span class="string">&quot;生产者发出消息:&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="消费者-4"><a href="#消费者-4" class="headerlink" title="消费者"></a>消费者</h3><blockquote>
<p><strong>消费者代码中，都需要加上<code>channel.basicQos(1);</code></strong></p>
</blockquote>
<h4 id="消费者1"><a href="#消费者1" class="headerlink" title="消费者1"></a>消费者1</h4><blockquote>
<p><strong>消费者1还在<code>DeliverCallback</code>回调接口中加入了睡眠的代码，表示业务处理时间较长</strong></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.CancelCallback;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.DeliverCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.SleepUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Date: 2023/5/24</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> XiaoFei</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerTwo</span> &#123;</span><br><span class="line">    <span class="comment">//队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TASK_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;QUEUE_MESSAGE&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//接受消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//推送的消息如何进行消费的接口回调，在该接口中进行消息消费</span></span><br><span class="line">        <span class="comment">//TODO 这里由于DeliverCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag, message) -&gt; &#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//沉睡1S</span></span><br><span class="line">            SleepUtils.sleep(<span class="number">3</span>);</span><br><span class="line">            System.out.println(<span class="string">&quot;接受到的消息:&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">            <span class="comment">//手动应答</span></span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * 1.消息的标记Tag</span></span><br><span class="line"><span class="comment">             * 2.是否批量应答 false表示不批量应答信道中的消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicAck(message.getEnvelope().getDeliveryTag(), <span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//取消消费的一个回调接口 如在消费的时候队列被删除掉了</span></span><br><span class="line">        <span class="comment">//TODO 这里由于CancelCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">CancelCallback</span> <span class="variable">cancelCallback</span> <span class="operator">=</span> (consumerTag -&gt; &#123;</span><br><span class="line">            System.out.println(consumerTag + <span class="string">&quot;消费者取消消费接口回调逻辑&quot;</span>);</span><br><span class="line"></span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置不公平分发</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">prefetchCount</span> <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line">        channel.basicQos(prefetchCount);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置参数值为false，设置为手动应答，手动应答的代码在DeliverCallback消费接口中进行实现</span></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">autoAck</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 消费者消费消息</span></span><br><span class="line"><span class="comment">         * 1.消费哪个队列</span></span><br><span class="line"><span class="comment">         * 2.消费成功之后是否要自动应答true：代表自动应答false:代表手动应答</span></span><br><span class="line"><span class="comment">         * 3.消费者未成功消费的回调</span></span><br><span class="line"><span class="comment">         * 4.消费者取消消费的回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, cancelCallback);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="消费者2"><a href="#消费者2" class="headerlink" title="消费者2"></a>消费者2</h4><blockquote>
<p><strong>消费者2还在<code>DeliverCallback</code>回调接口中没有加入了睡眠的代码，表示业务处理时间较短，可以处理较多的消息</strong></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.CancelCallback;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.DeliverCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消息消费者</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerThree</span> &#123;</span><br><span class="line">    <span class="comment">//队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TASK_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;QUEUE_MESSAGE&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//接受消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//推送的消息如何进行消费的接口回调，在该接口中进行消息消费</span></span><br><span class="line">        <span class="comment">//TODO 这里由于DeliverCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag, message) -&gt; &#123;</span><br><span class="line">            </span><br><span class="line">            System.out.println(<span class="string">&quot;接受到的消息:&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">            </span><br><span class="line">            <span class="comment">//手动应答</span></span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * 1.消息的标记Tag</span></span><br><span class="line"><span class="comment">             * 2.是否批量应答 false表示不批量应答信道中的消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicAck(message.getEnvelope().getDeliveryTag(), <span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//取消消费的一个回调接口 如在消费的时候队列被删除掉了</span></span><br><span class="line">        <span class="comment">//TODO 这里由于CancelCallback是个接口，所以这里直接使用了Java8提供的Lambda表达式实现了，没有另外再写一个类实现该接口</span></span><br><span class="line">        <span class="type">CancelCallback</span> <span class="variable">cancelCallback</span> <span class="operator">=</span> (consumerTag -&gt; &#123;</span><br><span class="line">            System.out.println(consumerTag + <span class="string">&quot;消费者取消消费接口回调逻辑&quot;</span>);</span><br><span class="line"></span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置不公平分发</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">prefetchCount</span> <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line">        channel.basicQos(prefetchCount);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置参数值为false，设置为手动应答，手动应答的代码在DeliverCallback消费接口中进行实现</span></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">autoAck</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 消费者消费消息</span></span><br><span class="line"><span class="comment">         * 1.消费哪个队列</span></span><br><span class="line"><span class="comment">         * 2.消费成功之后是否要自动应答true：代表自动应答false:代表手动应答</span></span><br><span class="line"><span class="comment">         * 3.消费者未成功消费的回调</span></span><br><span class="line"><span class="comment">         * 4.消费者取消消费的回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(TASK_QUEUE_NAME, autoAck, deliverCallback, cancelCallback);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="效果"><a href="#效果" class="headerlink" title="效果"></a>效果</h4><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230525150516234.png" alt="image-20230525150516234"></p>
<h2 id="预取值分发"><a href="#预取值分发" class="headerlink" title="预取值分发"></a>预取值分发</h2><p>RabbitMQ 是一种流行的消息代理，它允许应用程序之间通过消息传递进行通信。预取值（Prefetch）是 RabbitMQ 中用于控制消费者获取消息数量的机制之一，它指定一个消费者可以从队列中预取的未确认消息的最大数量。</p>
<p><strong>预取值为 1 是最保守的。当然这将使吞吐量变得很低，特别是消费者连接延迟很严重的情况下，特别是在消费者连接等待时间较长的环境 中。对于大多数应用来说，稍微高一点的值将是最佳的。</strong></p>
<blockquote>
<p><strong>此时有两个向消费者，如果生产者总共发布了五条消息，消费者1设置<code>basicQos(2)</code>，那消费者只能消费<code>两条</code>消息，消费者2设置<code>basicQos(3)</code>，那消费者只能消费<code>三条</code>消息，按比例进行消费</strong></p>
<p><strong>生产者和消费者代码和前面的不公平分发中生产者代码一样，只是<code>channel.basicQos(正整数);</code>设置的值不一致，来影响每个消费者可以消费的消息比例，避免消费者从队列中获取太多的消息而无法及时处理它们</strong></p>
</blockquote>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230525161925342.png" alt="image-20230525161925342"></p>
<h2 id="发布确认"><a href="#发布确认" class="headerlink" title="发布确认"></a>发布确认</h2><blockquote>
<p><strong>确认发布指的是成功发送到了队列，并不是消费者消费了消息</strong></p>
</blockquote>
<p>生产者发布消息到 RabbitMQ 后，需要 RabbitMQ 返回【 ACK（已收到）】给生产者，这样生产者才知道自己生产的消息成功发布出去</p>
<h3 id="发布确认逻辑"><a href="#发布确认逻辑" class="headerlink" title="发布确认逻辑"></a>发布确认逻辑</h3><p>生产者将信道设置成 confirm 模式，一旦信道进入 confirm 模式，所有在该信道上面发布的消息都将会被指派一个唯一的 ID(从 1 开始)，一旦消息被投递到所有匹配的队列之后，broker 就会发送一个确认给生产者(包含消息的唯一 ID)，这就使得生产者知道消息已经正确到达目的队列了，如果消息和队列是可持久化的，那么确认消息会在将消息写入磁盘之后发出，broker 回传给生产者的确认消息中 delivery-tag 域包含了确认消息的序列号，此外 broker 也可以设置 basic.ack 的 multiple 域，表示到这个序列号之前的所有消息都已经得到了处理。</p>
<p>confirm 模式最大的好处在于是异步的，一旦发布一条消息，生产者应用程序就可以在等信道返回确认的同时继续发送下一条消息，当消息最终得到确认之后，生产者应用便可以通过回调方法来处理该确认消息，如果RabbitMQ 因为自身内部错误导致消息丢失，就会发送一条 nack 消息， 生产者应用程序同样可以在回调方法中处理该 nack 消息</p>
<h3 id="开启发布确认方法"><a href="#开启发布确认方法" class="headerlink" title="开启发布确认方法"></a>开启发布确认方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在 channel.queueDeclare( ) 后，使用下面方法开启发布确认</span></span><br><span class="line">channel.confirmSelect();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在 channel.basicPublish() 将消息发布后，使用下面方法，确认消息发布</span></span><br><span class="line">channel.waitForConfirms();</span><br></pre></td></tr></table></figure>
<h3 id="单个确认发布"><a href="#单个确认发布" class="headerlink" title="单个确认发布"></a>单个确认发布</h3><p>这是一种简单的确认方式，它是一种<strong>同步确认发布</strong>的方式，也就是发布一个消息之后只有它被确认发布，后续的消息才能继续发布，<code>waitForConfirmsOrDie(long)</code> 这个方法只有在消息被确认的时候才返回，如果在指定时间范围内这个消息没有被确认那么它将抛出异常。</p>
<p>这种确认方式有一个最大的缺点就是：<strong>发布速度特别的慢</strong>，因为如果没有确认发布的消息就会阻塞所有后续消息的发布，这种方式最多提供每秒不超过数百条发布消息的吞吐量。当然对于某些应用程序来说这可能已经足够了。</p>
<blockquote>
<p><strong>下面为消息生产者的代码，由于确认发布是生产者的操作，所以这里不提供消费者代码了，发布确认代码使用了<code>TODO</code>标记</strong></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 单个确认发布</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerOne</span> &#123;</span><br><span class="line">    <span class="comment">//对列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;hello&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//发消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException, InterruptedException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//TODO 开启发布确认</span></span><br><span class="line">        channel.confirmSelect();</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 发送一个消息</span></span><br><span class="line"><span class="comment">         * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">         * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">         * 3.其他参数信息</span></span><br><span class="line"><span class="comment">         * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="literal">null</span>, (i + <span class="string">&quot;&quot;</span>).getBytes());</span><br><span class="line">            <span class="comment">//TODO 单个消息就马上进行发布确认</span></span><br><span class="line">            <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> channel.waitForConfirms();</span><br><span class="line">            <span class="keyword">if</span> (flag) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;消息发送完毕&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="批量确认发布"><a href="#批量确认发布" class="headerlink" title="批量确认发布"></a>批量确认发布</h3><blockquote>
<p><strong>批量确认和单个确认写法一致，只是执行<code>channel.waitForConfirms()</code>方法的时机不一致，批量确认是等消息发布了指定数量的时候，再执行该方法，单个确认发布是，消息一发布就立刻执行该方法</strong></p>
</blockquote>
<p>单个确认发布方式非常慢，与单个等待确认消息相比，先发布一批消息然后一起确认可以极大地提高吞吐量，当然这种方式的缺点就是：当发生故障导致发布出现问题时，不知道是哪个消息出问题了，我们必须将整个批处理保存在内存中，以记录重要的信息而后重新发布消息。当然这种方案仍然是同步的，也一样阻塞消息的发布。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消息生产者批量确认发布</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerOne</span> &#123;</span><br><span class="line">    <span class="comment">//对列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;hello&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//发消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException, InterruptedException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//TODO 开启发布确认</span></span><br><span class="line">        channel.confirmSelect();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//TODO 批量确认消息大小，当消息发布多少条后进行发布确认</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">batchSize</span> <span class="operator">=</span> <span class="number">100</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 发送一个消息</span></span><br><span class="line"><span class="comment">         * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">         * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">         * 3.其他参数信息</span></span><br><span class="line"><span class="comment">         * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">1000</span>; i++) &#123;</span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="literal">null</span>, (i + <span class="string">&quot;&quot;</span>).getBytes());</span><br><span class="line"></span><br><span class="line">            <span class="comment">//TODO 判断达到100条消息的时候，批量确认一次</span></span><br><span class="line">            <span class="keyword">if</span> ((i + <span class="number">1</span>) % batchSize == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">//TODO 发布确认</span></span><br><span class="line">                channel.waitForConfirms();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="异步确认"><a href="#异步确认" class="headerlink" title="异步确认"></a>异步确认</h3><p>异步确认虽然编程逻辑比上两个要复杂，但是性价比最高，无论是可靠性还是效率都很好，利用了回调函数来达到消息可靠性传递的，这个中间件也是通过函数回调来保证是否投递成功，下面详细讲解异步确认是怎么实现的。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/202305231852001.png" alt="202305231852001"></p>
<p>实际案例里，将发布的消息存入 Map 里，方便获取。<code>headMap</code> 方法用于将已确认的消息存入新的 Map 缓存区里，然后清除该新缓存区的内容。因为 <code>headMap</code> 方法是浅拷贝，所以清除了缓存区，相当于清除了内容的地址，也就清除了队列的确认的消息。</p>
<p><strong>未处理异步未确认消息代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConfirmCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 异步确认消息发布（未处理异步未确认消息代码）</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerOne</span> &#123;</span><br><span class="line">    <span class="comment">//对列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;hello&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//发消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException, InterruptedException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//开启发布确认</span></span><br><span class="line">        channel.confirmSelect();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//消息确认回调的函数</span></span><br><span class="line">        <span class="type">ConfirmCallback</span> <span class="variable">ackCallback</span> <span class="operator">=</span> (deliveryTag, multiple) -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;确认的消息:&quot;</span> + deliveryTag);</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 消息确认失败回调函数</span></span><br><span class="line"><span class="comment">         * 1.消息的标记</span></span><br><span class="line"><span class="comment">         * 2.是否为批量确认</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="type">ConfirmCallback</span> <span class="variable">nackCallback</span> <span class="operator">=</span> (deliveryTag, multiple) -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;未确认的消息:&quot;</span> + deliveryTag);</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 异步通知</span></span><br><span class="line"><span class="comment">         * 准备消息的监听器 监听那些消息成功了，哪些消息失败了</span></span><br><span class="line"><span class="comment">         * 1.监听哪些消息成功了</span></span><br><span class="line"><span class="comment">         * 2.监听哪些消息失败了</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.addConfirmListener(ackCallback, nackCallback);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 发送一个消息</span></span><br><span class="line"><span class="comment">         * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">         * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">         * 3.其他参数信息</span></span><br><span class="line"><span class="comment">         * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">1000</span>; i++) &#123;</span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="literal">null</span>, (i + <span class="string">&quot;&quot;</span>).getBytes());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>处理异步未确认消息代码</strong></p>
<blockquote>
<p><strong>最好的解决的解决方案就是把未确认的消息放到一个基于内存的能被发布线程访问的队列，比如说用 ConcurrentLinkedQueue 这个队列在 confirm callbacks 与发布线程之间进行消息的传递。</strong></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConfirmCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.ConcurrentNavigableMap;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.ConcurrentSkipListMap;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 异步确认消息发布（处理异步未确认消息代码）</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerOne</span> &#123;</span><br><span class="line">    <span class="comment">//对列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;hello&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//发消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException, InterruptedException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//开启发布确认</span></span><br><span class="line">        channel.confirmSelect();</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 线程安全有序的一个哈希表，适用于高并发的情况下</span></span><br><span class="line"><span class="comment">         * 1.轻松的将序号与消息进行关联</span></span><br><span class="line"><span class="comment">         * 2.轻松批量删除条目 只要给到序号</span></span><br><span class="line"><span class="comment">         * 3.支持高并发(多线程)</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        ConcurrentSkipListMap&lt;Long, String&gt; outstandingConfirms =</span><br><span class="line">                <span class="keyword">new</span> <span class="title class_">ConcurrentSkipListMap</span>&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//消息确认回调的函数</span></span><br><span class="line">        <span class="type">ConfirmCallback</span> <span class="variable">ackCallback</span> <span class="operator">=</span> (deliveryTag, multiple) -&gt; &#123;</span><br><span class="line">            <span class="keyword">if</span> (multiple) &#123;</span><br><span class="line">                <span class="comment">//2.删除掉已经确认的消息 剩下的就是未确认的消息</span></span><br><span class="line">                ConcurrentNavigableMap&lt;Long, String&gt; confirmed =</span><br><span class="line">                        outstandingConfirms.headMap(deliveryTag);</span><br><span class="line">                confirmed.clear();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                outstandingConfirms.remove(deliveryTag);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;确认的消息:&quot;</span> + deliveryTag);</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 消息确认失败回调函数</span></span><br><span class="line"><span class="comment">         * 1.消息的标记</span></span><br><span class="line"><span class="comment">         * 2.是否为批量确认</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="type">ConfirmCallback</span> <span class="variable">nackCallback</span> <span class="operator">=</span> (deliveryTag, multiple) -&gt; &#123;</span><br><span class="line">            <span class="comment">//3.打印一下未确认的消息都有哪些</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> outstandingConfirms.remove(deliveryTag);</span><br><span class="line">            System.out.println(<span class="string">&quot;未确认的消息是:&quot;</span> + message + <span class="string">&quot;:::未确认的消息tag:&quot;</span> + deliveryTag);</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 异步通知</span></span><br><span class="line"><span class="comment">         * 准备消息的监听器 监听那些消息成功了，哪些消息失败了</span></span><br><span class="line"><span class="comment">         * 1.监听哪些消息成功了</span></span><br><span class="line"><span class="comment">         * 2.监听哪些消息失败了</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.addConfirmListener(ackCallback, nackCallback);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 发送一个消息</span></span><br><span class="line"><span class="comment">         * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">         * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">         * 3.其他参数信息</span></span><br><span class="line"><span class="comment">         * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">1000</span>; i++) &#123;</span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="literal">null</span>, (i + <span class="string">&quot;&quot;</span>).getBytes());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="三种发布确认方式对比"><a href="#三种发布确认方式对比" class="headerlink" title="三种发布确认方式对比"></a>三种发布确认方式对比</h3><ul>
<li>单独发布消息：同步等待确认，简单，但吞吐量非常有限。</li>
<li>批量发布消息：批量同步等待确认，简单，合理的吞吐量，一旦出现问题但很难推断出是那条消息出现了问题。</li>
<li>异步处理：最佳性能和资源使用，在出现错误的情况下可以很好地控制，但是实现起来稍微难些</li>
</ul>
<h2 id="消息应答和发布确认的区别"><a href="#消息应答和发布确认的区别" class="headerlink" title="消息应答和发布确认的区别"></a>消息应答和发布确认的区别</h2><p>消息应答：属于消费者，消费完消息告诉 RabbitMQ 已经消费成功</p>
<p>发布确认：属于生产者，生产消息到 RabbitMQ，RabbitMQ 需要告诉生产者已经收到消息</p>
<h1 id="交换机"><a href="#交换机" class="headerlink" title="交换机"></a>交换机</h1><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230526172345156.png" alt="image-20230526172345156"></p>
<h2 id="交换机（Exchanges）"><a href="#交换机（Exchanges）" class="headerlink" title="交换机（Exchanges）"></a>交换机（Exchanges）</h2><p>RabbitMQ 消息传递模型的核心思想是：<strong>生产者生产的消息从不会直接发送到队列</strong>。实际上，通常生产者甚至都不知道这些消息传递传递到了哪些队列中。</p>
<p>相反，<strong>生产者只能将消息发送到交换机(exchange)</strong>，交换机工作的内容非常简单，一方面它接收来自生产者的消息，另一方面将它们推入队列。交换机必须确切知道如何处理收到的消息。是应该把这些消息放到特定队列还是说把他们到许多队列中还是说应该丢弃它们。这就的由交换机的类型来决定。</p>
<h2 id="交换机类型"><a href="#交换机类型" class="headerlink" title="交换机类型"></a>交换机类型</h2><ul>
<li><p><strong>直接(direct)</strong>：处理路由键。需要将一个队列绑定到交换机上，要求该消息与一个特定的路由键完全匹配。这是一个完整的匹配。如果一个队列绑定到该交换机上要求路由键 abc ，则只有被标记为 abc 的消息才被转发，不会转发 abc.def，也不会转发 dog.ghi，只会转发 abc。</p>
</li>
<li><p><strong>主题(topic)</strong>：将路由键和某模式进行匹配。此时队列需要绑定要一个模式上。符号“#”匹配一个或多个词，符号 <em> 匹配不多不少一个词。因此 abc.# 能够匹配到 abc.def.ghi，但是 abc.</em> 只会匹配到 abc.def。</p>
</li>
<li><p><strong>标题(headers)</strong>：不处理路由键。而是根据发送的消息内容中的headers属性进行匹配。在绑定 Queue 与 Exchange 时指定一组键值对；当消息发送到RabbitMQ 时会取到该消息的 headers 与 Exchange 绑定时指定的键值对进行匹配；如果完全匹配则消息会路由到该队列，否则不会路由到该队列。headers 属性是一个键值对，可以是 Hashtable，键值对的值可以是任何类型。而 fanout，direct，topic 的路由键都需要要字符串形式的。</p>
<ul>
<li>匹配规则 x-match 有下列两种类型：<ul>
<li>x-match = all ：表示所有的键值对都匹配才能接受到消息</li>
<li>x-match = any ：表示只要有键值对匹配就能接受到消息</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>扇出(fanout)</strong>：不处理路由键。你只需要简单的将队列绑定到交换机上。一个发送到交换机的消息都会被转发到与该交换机绑定的所有队列上。很像子网广播，每台子网内的主机都获得了一份复制的消息。Fanout 交换机转发消息是最快的。<code>类似于，多个人关注一个公众号，该公众号发布消息，所有订阅的人都能收到消息</code></p>
</li>
<li><p><strong>默认</strong>：通过空字符串(“”)进行标识的交换机是默认交换</p>
  <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 第一个参数是交换机的名称。空字符串 表示默认或无名称交换机：消息能路由发送到队列中其实是由 routingKey(bindingkey) 绑定指定的 key</span></span><br><span class="line">channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="literal">null</span>, message.getBytes(<span class="string">&quot;UTF-8&quot;</span>));</span><br></pre></td></tr></table></figure>
<p>  <img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230526172615744.png" alt="image-20230526172615744"></p>
</li>
</ul>
<h2 id="临时队列"><a href="#临时队列" class="headerlink" title="临时队列"></a>临时队列</h2><p>之前的使用的是具有特定名称的队列(还记得 hello 和 ack_queue 吗？)。队列的名称我们来说至关重要，我们需要指定我们的消费者去消费哪个队列的消息。</p>
<p>每当我们连接到 Rabbit 时，我们都需要一个全新的空队列，为此我们可以创建一个具有<strong>随机名称的队列</strong>，或者能让服务器为我们选择一个随机队列名称那就更好了。其次一旦我们断开了消费者的连接，队列将被自动删除。</p>
<p>创建临时队列的方式如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取创建的临时队列名称</span></span><br><span class="line"><span class="type">String</span> <span class="variable">queueName</span> <span class="operator">=</span> channel.queueDeclare().getQueue();</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 创建临时队列</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerTwo</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TASK_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;QUEUE_MESSAGE&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">//获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 创建临时队列并且获取创建的临时队列的名称</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">queueName</span> <span class="operator">=</span> channel.queueDeclare().getQueue();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生产一个对列</span></span><br><span class="line"><span class="comment">         * 1.对列名称</span></span><br><span class="line"><span class="comment">         * 2.对列里面的消息是否持久化，默认情况下，消息存储在内存中</span></span><br><span class="line"><span class="comment">         * 3.该队列是否只供一个消费者进行消费，是否进行消息共享，true可以多个消费者消费 false：只能一个消费者消费</span></span><br><span class="line"><span class="comment">         * 4.是否自动删除，最后一个消费者端开链接以后，该队列是否自动删除，true表示自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(queueName, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//在控制台中输入需要生产的信息</span></span><br><span class="line">        <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">        System.out.println(<span class="string">&quot;请输入信息：&quot;</span>);</span><br><span class="line">        <span class="keyword">while</span> (scanner.hasNext()) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> scanner.next();</span><br><span class="line"></span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * 发送一个消息</span></span><br><span class="line"><span class="comment">             * 1.发送到哪个交换机</span></span><br><span class="line"><span class="comment">             * 2.路由的key值是哪个本次是队列的名称</span></span><br><span class="line"><span class="comment">             * 3.其他参数信息，这使用【MessageProperties.PERSISTENT_TEXT_PLAIN】开启消息持久化</span></span><br><span class="line"><span class="comment">             * 4.发送消息的消息体</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, queueName, <span class="literal">null</span>, message.getBytes(StandardCharsets.UTF_8));</span><br><span class="line"></span><br><span class="line">            System.out.println(<span class="string">&quot;生产者发出消息:&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230526173242830.png" alt="image-20230526173242830"></p>
<h2 id="绑定交换机（绑定bindings）"><a href="#绑定交换机（绑定bindings）" class="headerlink" title="绑定交换机（绑定bindings）"></a>绑定交换机（绑定bindings）</h2><p>什么是 bingding 呢，binding 其实是 exchange 和 queue 之间的桥梁，它告诉我们 exchange 和那个队列进行了绑定关系。比如说下面这张图告诉我们的就是 交换机 与 队列1 和 队列2 进行了绑定</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230526192930194.png" alt="image-20230526192930194"></p>
<h2 id="各类型交换机使用"><a href="#各类型交换机使用" class="headerlink" title="各类型交换机使用"></a>各类型交换机使用</h2><h3 id="Fanout"><a href="#Fanout" class="headerlink" title="Fanout"></a>Fanout</h3><p>为了说明这种模式，我们将构建一个简单的日志系统。它将由两个程序组成:第一个程序将发出日志消息，第二个程序是消费者。其中启动两个消费者，其中一个消费者接收到消息后把日志存储在磁盘</p>
<h4 id="生产者-5"><a href="#生产者-5" class="headerlink" title="生产者"></a>生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消息生产者将消息发送给交换机</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerOne</span> &#123;</span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">// 获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 创建一个exchange（交换机）</span></span><br><span class="line"><span class="comment">         * 1.exchange的名称</span></span><br><span class="line"><span class="comment">         * 2.exchange的类型</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);</span><br><span class="line">        </span><br><span class="line">        <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> (scanner.hasNext()) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> scanner.next();</span><br><span class="line">            </span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">  			 * 发送消息给指定的交换机</span></span><br><span class="line"><span class="comment">             * exchange（交换器）：一个字符串，表示消息将要发送到哪个交换器。</span></span><br><span class="line"><span class="comment">             * routing_key（路由键）：一个字符串，表示消息的路由键，用于选择与该路由键匹配的队列。</span></span><br><span class="line"><span class="comment">             * properties（属性）：一个AMQP属性对象，用于携带一些额外的元数据（如消息类型、优先级等）。</span></span><br><span class="line"><span class="comment">             * body（消息体）：一个字节数组，表示消息的内容。</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicPublish(EXCHANGE_NAME, <span class="string">&quot;&quot;</span>, <span class="literal">null</span>, message.getBytes(<span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">            System.out.println(<span class="string">&quot;生产者发出消息:&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="消费者-5"><a href="#消费者-5" class="headerlink" title="消费者"></a>消费者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.DeliverCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消费者，通过帮会顶的</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerOne</span> &#123;</span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">// 获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明一个交换机【交换机名称，交换机类型】</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 生成一个临时的队列，队列的名称是随机的</span></span><br><span class="line"><span class="comment">         * 当消费者断开与队列的连接的时候 队列就自动删除</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">queueName</span> <span class="operator">=</span> channel.queueDeclare().getQueue();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 绑定交换机与队列【队列名称、交换机名称、交换机和队列绑定的RoutingKey】</span></span><br><span class="line">        channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">&quot;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;等待接收消息，把接收到的消息打印在屏幕上...&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//消费者取消消息时回调接口</span></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag, message) -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;控制台打印接收到的消息:&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 消费者消费消息</span></span><br><span class="line">        channel.basicConsume(queueName, <span class="literal">true</span>, deliverCallback, consumerTag -&gt; &#123;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>结果：生产者将消息发送给绑定的队列，消费者从绑定的队列中获取消息，都能获取到，<code>类似于，多个人关注一个公众号，该公众号发布消息，所有订阅的人都能收到消息</code></strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230526193106406.png" alt="image-20230526193106406"></p>
<h3 id="Direct"><a href="#Direct" class="headerlink" title="Direct"></a>Direct</h3><p>在上一节中，我们构建了一个简单的日志记录系统。我们能够向许多接收者广播日志消息。在本节我们将向其中添加一些特别的功能——让某个消费者订阅发布的部分消息。例如我们只把严重错误消息定向存储到日志文件(以节省磁盘空间)，同时仍然能够在控制台上打印所有日志消息。</p>
<p>我们再次来回顾一下什么是 bindings，绑定是交换机和队列之间的桥梁关系。也可以这么理解： <strong>队列只对它绑定的交换机的消息感兴趣</strong>。绑定用参数：routingKey 来表示也可称该参数为 binding key， 创建绑定我们用代码:channel.queueBind(queueName, EXCHANGE_NAME, “routingKey”);</p>
<p>绑定之后的意义由其交换类型决定。</p>
<h4 id="Direct介绍"><a href="#Direct介绍" class="headerlink" title="Direct介绍"></a>Direct介绍</h4><p>上一节中的我们的日志系统将所有消息广播给所有消费者，对此我们想做一些改变，例如我们希望将日志消息写入磁盘的程序仅接收严重错误(errros)，而不存储哪些警告(warning)或信息(info)日志 消息避免浪费磁盘空间。Fanout 这种交换类型并不能给我们带来很大的灵活性-它只能进行无意识的广播，在这里我们将使用 direct 这种类型来进行替换，这种类型的工作方式是，消息只去到它绑定的 routingKey 队列中去。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230529095924798.png" alt="image-20230529095924798"></p>
<p>在上面这张图中，我们可以看到 X 绑定了两个队列，绑定类型是 direct。队列1 绑定键为 orange， 队列2 绑定键有两个：一个绑定键为 black，另一个绑定键为 green.</p>
<p>在这种绑定情况下，生产者发布消息到 exchange 上，绑定键为 orange 的消息会被发布到队列1。绑定键为 black或green的消息会被发布到队列2，其他消息类型的消息将被丢弃。</p>
<h4 id="多重绑定"><a href="#多重绑定" class="headerlink" title="多重绑定"></a>多重绑定</h4><p>当然如果 exchange 的绑定类型是direct，<strong>但是它绑定的多个队列的 key 如果都相同</strong>，在这种情况下虽然绑定类型是 direct <strong>但是它表现的就和 fanout 有点类似了</strong>，就跟广播差不多，如上图所示。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230529100107558.png" alt="image-20230529100107558"></p>
<h4 id="生产者-6"><a href="#生产者-6" class="headerlink" title="生产者"></a>生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * direct类型交换机测试</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerOne</span> &#123;</span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;direct_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">        <span class="keyword">while</span> (scanner.hasNext()) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> scanner.next();</span><br><span class="line">            <span class="comment">// orange是routingKey，可以变换</span></span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">             * exchange（交换器）：一个字符串，表示消息将要发送到哪个交换器。</span></span><br><span class="line"><span class="comment">             * routing_key（路由键）：一个字符串，表示消息的路由键，用于选择与该路由键匹配的队列。</span></span><br><span class="line"><span class="comment">             * properties（属性）：一个AMQP属性对象，用于携带一些额外的元数据（如消息类型、优先级等）。</span></span><br><span class="line"><span class="comment">             * body（消息体）：一个字节数组，表示消息的内容。</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicPublish(EXCHANGE_NAME, <span class="string">&quot;orange&quot;</span>, <span class="literal">null</span>, message.getBytes(<span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">            System.out.println(<span class="string">&quot;生产者发出消息:&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="消费者1-1"><a href="#消费者1-1" class="headerlink" title="消费者1"></a>消费者1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.DeliverCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消费者1，routingKey：orange</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerOne</span> &#123;</span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;direct_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;person&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">// 获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明一个交换机【交换机名称，交换机类型】</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 队列名称。</span></span><br><span class="line"><span class="comment">         * 指定队列是否需要持久化。</span></span><br><span class="line"><span class="comment">         * 指定队列是否为独占队列。</span></span><br><span class="line"><span class="comment">         * 指定队列是否自动删除。</span></span><br><span class="line"><span class="comment">         * 用于设置队列的其他属性，例如 TTL、最大长度等。</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 绑定交换机与队列【队列名称、交换机名称、交换机和队列绑定的RoutingKey】</span></span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;orange&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;等待接收消息，把接收到的消息打印在屏幕上...&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//消费者取消消息时回调接口</span></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag, message) -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;exchange：direct_exchange\nqueue：person\nroutingKey：orange\n消息：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 消费者消费消息</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="literal">true</span>, deliverCallback, consumerTag -&gt; &#123;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="消费者2-1"><a href="#消费者2-1" class="headerlink" title="消费者2"></a>消费者2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.DeliverCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消费者2，routingKey：black</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerTwo</span> &#123;</span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;direct_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;user&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="comment">// 获取信道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明一个交换机【交换机名称，交换机类型】</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * 队列名称。</span></span><br><span class="line"><span class="comment">         * 指定队列是否需要持久化。</span></span><br><span class="line"><span class="comment">         * 指定队列是否为独占队列。</span></span><br><span class="line"><span class="comment">         * 指定队列是否自动删除。</span></span><br><span class="line"><span class="comment">         * 用于设置队列的其他属性，例如 TTL、最大长度等。</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 绑定交换机与队列【队列名称、交换机名称、交换机和队列绑定的RoutingKey】</span></span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;black&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;等待接收消息，把接收到的消息打印在屏幕上...&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//消费者取消消息时回调接口</span></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag, message) -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;exchange：direct_exchange\nqueue：user\nroutingKey：black\n消息：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 消费者消费消息</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="literal">true</span>, deliverCallback, consumerTag -&gt; &#123;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="结果"><a href="#结果" class="headerlink" title="结果"></a>结果</h4><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230529104022902.png" alt="image-20230529104022902"></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230529104243705.png" alt="image-20230529104243705"></p>
<h3 id="Topics"><a href="#Topics" class="headerlink" title="Topics"></a>Topics</h3><h4 id="Topic的介绍"><a href="#Topic的介绍" class="headerlink" title="Topic的介绍"></a>Topic的介绍</h4><p>在上一个小节中，我们改进了日志记录系统。我们没有使用只能进行随意广播的 fanout 交换机，而是使用了 direct 交换机，从而有能实现有选择性地接收日志。</p>
<p>尽管使用 direct 交换机改进了我们的系统，但是它仍然存在局限性——比方说我们想接收的日志类型有 info.base 和 info.advantage，某个队列只想 info.base 的消息，那这个时候direct 就办不到了。这个时候就只能使用 <strong>topic</strong> 类型</p>
<p><strong>Topic 的要求</strong></p>
<p>发送到类型是 topic 交换机的消息的 routing_key 不能随意写，必须满足一定的要求，它必须是<strong>一个单词列表</strong>，<strong>以点号分隔开</strong>。这些单词可以是任意单词</p>
<p>比如说：”stock.usd.nyse”, “nyse.vmw”, “quick.orange.rabbit” 这种类型的。</p>
<p>当然这个单词列表最多不能超过 255 个字节。</p>
<p>在这个规则列表中，其中有两个替换符是大家需要注意的：</p>
<ul>
<li><strong>*(星号)可以代替一个位置</strong></li>
<li><strong>#(井号)可以替代零个或多个位置</strong></li>
</ul>
<h4 id="Topic匹配案例"><a href="#Topic匹配案例" class="headerlink" title="Topic匹配案例"></a>Topic匹配案例</h4><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230529105705819.png" alt="image-20230529105705819"></p>
<ul>
<li>Q1—&gt;绑定的是<ul>
<li>中间带 orange 带 3 个单词的字符串 <code>(*.orange.*)</code></li>
</ul>
</li>
<li>Q2—&gt;绑定的是<ul>
<li>最后一个单词是 rabbit 的 3 个单词 <code>(*.*.rabbit)</code></li>
<li>第一个单词是 lazy 的多个单词 <code>(lazy.#)</code></li>
</ul>
</li>
</ul>
<p>上图是一个队列绑定关系图，我们来看看他们之间数据接收情况是怎么样的</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>例子</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>quick.orange.rabbit</td>
<td>被队列 Q1Q2 接收到</td>
</tr>
<tr>
<td>azy.orange.elephant</td>
<td>被队列 Q1Q2 接收到</td>
</tr>
<tr>
<td>quick.orange.fox</td>
<td>被队列 Q1 接收到</td>
</tr>
<tr>
<td>lazy.brown.fox</td>
<td>被队列 Q2 接收到</td>
</tr>
<tr>
<td>lazy.pink.rabbit</td>
<td>虽然满足两个绑定但只被队列 Q2 接收一次</td>
</tr>
<tr>
<td>quick.brown.fox</td>
<td>不匹配任何绑定不会被任何队列接收到会被丢弃</td>
</tr>
<tr>
<td>quick.orange.male.rabbit</td>
<td>是四个单词不匹配任何绑定会被丢弃</td>
</tr>
<tr>
<td>lazy.orange.male.rabbit</td>
<td>是四个单词但匹配 Q2</td>
</tr>
</tbody>
</table>
</div>
<blockquote>
<p><strong>当一个队列绑定键是 #，那么这个队列将接收所有数据，就有点像 fanout 了</strong></p>
<p><strong>如果队列绑定键当中没有 # 和 * 出现，那么该队列绑定类型就是 direct 了</strong></p>
</blockquote>
<h4 id="生产者-7"><a href="#生产者-7" class="headerlink" title="生产者"></a>生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * topics类型交换机测试</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerOne</span> &#123;</span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;topic_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">         * Q1--&gt;绑定的是</span></span><br><span class="line"><span class="comment">         *      中间带 orange 带 3 个单词的字符串(*.orange.*)</span></span><br><span class="line"><span class="comment">         * Q2--&gt;绑定的是</span></span><br><span class="line"><span class="comment">         *      最后一个单词是 rabbit 的 3 个单词(*.*.rabbit)</span></span><br><span class="line"><span class="comment">         *      第一个单词是 lazy 的多个单词(lazy.#)</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        HashMap&lt;String, String&gt; bindingKeyMap = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        bindingKeyMap.put(<span class="string">&quot;quick.orange.rabbit&quot;</span>, <span class="string">&quot;被队列 Q1Q2 接收到&quot;</span>);</span><br><span class="line">        bindingKeyMap.put(<span class="string">&quot;lazy.orange.elephant&quot;</span>, <span class="string">&quot;被队列 Q1Q2 接收到&quot;</span>);</span><br><span class="line">        bindingKeyMap.put(<span class="string">&quot;quick.orange.fox&quot;</span>, <span class="string">&quot;被队列 Q1 接收到&quot;</span>);</span><br><span class="line">        bindingKeyMap.put(<span class="string">&quot;lazy.brown.fox&quot;</span>, <span class="string">&quot;被队列 Q2 接收到&quot;</span>);</span><br><span class="line">        bindingKeyMap.put(<span class="string">&quot;lazy.pink.rabbit&quot;</span>, <span class="string">&quot;虽然满足两个绑定但只被队列 Q2 接收一次&quot;</span>);</span><br><span class="line">        bindingKeyMap.put(<span class="string">&quot;quick.brown.fox&quot;</span>, <span class="string">&quot;不匹配任何绑定不会被任何队列接收到会被丢弃&quot;</span>);</span><br><span class="line">        bindingKeyMap.put(<span class="string">&quot;quick.orange.male.rabbit&quot;</span>, <span class="string">&quot;是四个单词不匹配任何绑定会被丢弃&quot;</span>);</span><br><span class="line">        bindingKeyMap.put(<span class="string">&quot;lazy.orange.male.rabbit&quot;</span>, <span class="string">&quot;是四个单词但匹配 Q2&quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> (Map.Entry&lt;String, String&gt; bindingKeyEntry : bindingKeyMap.entrySet()) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">routingKey</span> <span class="operator">=</span> bindingKeyEntry.getKey();</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> bindingKeyEntry.getValue();</span><br><span class="line"></span><br><span class="line">            channel.basicPublish(EXCHANGE_NAME, routingKey, <span class="literal">null</span>, message.getBytes(<span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">            System.out.println(<span class="string">&quot;生产者发出消息:&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="消费者1-2"><a href="#消费者1-2" class="headerlink" title="消费者1"></a>消费者1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.DeliverCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * topics类型交换机消息接收</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerOne</span> &#123;</span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;topic_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//接收消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        <span class="comment">//声明交换机</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);</span><br><span class="line">        <span class="comment">//声明队列</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">queueName</span> <span class="operator">=</span> <span class="string">&quot;Q1&quot;</span>;</span><br><span class="line">        channel.queueDeclare(queueName,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">null</span>);</span><br><span class="line">        channel.queueBind(queueName,EXCHANGE_NAME,<span class="string">&quot;*.orange.*&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;等待接收消息...&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag,message) -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(),<span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">            System.out.println(<span class="string">&quot;接收队列：&quot;</span>+queueName+<span class="string">&quot;  绑定键:&quot;</span>+message.getEnvelope().getRoutingKey());</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//接收消息</span></span><br><span class="line">        channel.basicConsume(queueName,<span class="literal">true</span>,deliverCallback,consumerTag -&gt;&#123;&#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="消费者2-2"><a href="#消费者2-2" class="headerlink" title="消费者2"></a>消费者2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.DeliverCallback;</span><br><span class="line"><span class="keyword">import</span> com.xiaofei.rabbitmq.utils.ChannelUtils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * topics类型交换机消息接收</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerTwo</span> &#123;</span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;topic_exchange&quot;</span>;</span><br><span class="line">    <span class="comment">//接收消息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line">        <span class="comment">//声明交换机</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);</span><br><span class="line">        <span class="comment">//声明队列</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">queueName</span> <span class="operator">=</span> <span class="string">&quot;Q2&quot;</span>;</span><br><span class="line">        channel.queueDeclare(queueName,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">null</span>);</span><br><span class="line">        channel.queueBind(queueName,EXCHANGE_NAME,<span class="string">&quot;*.*.rabbit&quot;</span>);</span><br><span class="line">        channel.queueBind(queueName,EXCHANGE_NAME,<span class="string">&quot;lazy.#&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;等待接收消息...&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag,message) -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(),<span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">            System.out.println(<span class="string">&quot;接收队列：&quot;</span>+queueName+<span class="string">&quot;  绑定键:&quot;</span>+message.getEnvelope().getRoutingKey());</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//接收消息</span></span><br><span class="line">        channel.basicConsume(queueName,<span class="literal">true</span>,deliverCallback,consumerTag -&gt;&#123;&#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="结果-1"><a href="#结果-1" class="headerlink" title="结果"></a>结果</h4><p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230529110312371.png" alt="image-20230529110312371"></p>
<h1 id="死信队列"><a href="#死信队列" class="headerlink" title="死信队列"></a>死信队列</h1><h2 id="死信概念"><a href="#死信概念" class="headerlink" title="死信概念"></a>死信概念</h2><p>先从概念解释上搞清楚这个定义，死信，顾名思义就是无法被消费的消息，字面意思可以这样理解，一般来说，producer 将消息投递到 broker 或者直接到queue 里了，consumer 从 queue 取出消息 进行消费，但某些时候由于特定的原因<strong>导致 queue 中的某些消息无法被消费</strong>，这样的消息如果没有后续的处理，就变成了死信，有死信自然就有了死信队列。</p>
<p>应用场景：为了保证订单业务的消息数据不丢失，需要使用到 RabbitMQ 的死信队列机制，当消息消费发生异常时，将消息投入死信队列中。还有比如说：用户在商城下单成功并点击去支付后在指定时间未支付时自动失效。</p>
<h2 id="死信的来源"><a href="#死信的来源" class="headerlink" title="死信的来源"></a>死信的来源</h2><ul>
<li><p>消息 TTL 过期</p>
<p>  TTL是 Time To Live 的缩写, 也就是生存时间</p>
</li>
<li><p>队列达到最大长度</p>
<p>  队列满了，无法再添加数据到 MQ 中</p>
</li>
<li><p>消息被拒绝</p>
<p>  (basic.reject 或 basic.nack) 并且 requeue = false</p>
</li>
</ul>
<h2 id="死信实战"><a href="#死信实战" class="headerlink" title="死信实战"></a>死信实战</h2><p>交换机类型是 direct，两个消费者，一个生产者，两个队列：消息队列和死信队列</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.691xh9mh3yk0.webp" alt="image"></p>
<h3 id="消息TTL过期"><a href="#消息TTL过期" class="headerlink" title="消息TTL过期"></a>消息TTL过期</h3><p><strong>生产者</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> frx</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 1.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2022/7/25  19:13</span></span><br><span class="line"><span class="comment"> * desc:死信队列之生产者</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer</span> &#123;</span><br><span class="line">    <span class="comment">//普通交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">NORMAL_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;normal_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//死信消息 设置ttl时间 live to time 单位是ms</span></span><br><span class="line">        AMQP.<span class="type">BasicProperties</span> <span class="variable">properties</span> <span class="operator">=</span></span><br><span class="line">                <span class="keyword">new</span> <span class="title class_">AMQP</span>.BasicProperties().builder().expiration(<span class="string">&quot;10000&quot;</span>).build();</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt;<span class="number">11</span> ; i++) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;info&quot;</span>+i;</span><br><span class="line">            channel.basicPublish(NORMAL_EXCHANGE,<span class="string">&quot;zhangsan&quot;</span>,properties,message.getBytes());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>消费者 C1 代码</strong>(启动之后关闭该消费者 模拟其接收不到消息)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> frx</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 1.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2022/7/25  17:00</span></span><br><span class="line"><span class="comment"> * desc:本次是为了死信队列实战</span></span><br><span class="line"><span class="comment"> * 消费者1</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer01</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//普通交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">NORMAL_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;normal_exchange&quot;</span>;</span><br><span class="line">    <span class="comment">//死信交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;dead_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//普通队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">NORMAL_QUEUE</span> <span class="operator">=</span> <span class="string">&quot;normal_queue&quot;</span>;</span><br><span class="line">    <span class="comment">//死信队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_QUEUE</span> <span class="operator">=</span> <span class="string">&quot;dead_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明死信和普通交换机，类型为direct</span></span><br><span class="line">        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);</span><br><span class="line">        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明普通队列</span></span><br><span class="line">        Map&lt;String,Object&gt; arguments = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        <span class="comment">//过期时间 10s 由生产者指定 更加灵活</span></span><br><span class="line">        <span class="comment">//arguments.put(&quot;x-message-ttl&quot;,10000);</span></span><br><span class="line">        <span class="comment">//正常的队列设置死信交换机</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-exchange&quot;</span>,DEAD_EXCHANGE);<span class="comment">//图中红箭头</span></span><br><span class="line">        <span class="comment">//设置死信routingKey</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-routing-key&quot;</span>,<span class="string">&quot;lisi&quot;</span>);</span><br><span class="line"></span><br><span class="line">        channel.queueDeclare(NORMAL_QUEUE,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">false</span>,arguments);</span><br><span class="line">        <span class="comment">/////////////////////////////////////////////////////////////////////////</span></span><br><span class="line">        <span class="comment">//声明死信队列</span></span><br><span class="line">        channel.queueDeclare(DEAD_QUEUE,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//绑定普通的交换机与队列</span></span><br><span class="line">        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//绑定死信的交换机与死信的队列</span></span><br><span class="line">        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,<span class="string">&quot;lisi&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;等待接收消息...&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag,message) -&gt;&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;Consumer01接受的消息是：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(),<span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        channel.basicConsume(NORMAL_QUEUE,<span class="literal">true</span>,deliverCallback,consumerTag -&gt; &#123;&#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>先启动消费者 C1，创建出队列，然后停止该 C1 的运行，则 C1 将无法收到队列的消息，无法收到的消息 10 秒后进入死信队列。启动生产者 producer 生产消息</p>
<p><strong>生产者未发送消息</strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.5ldx5kffws00.webp" alt="image"></p>
<p><strong>生产者发送了10条消息，此时正常消息队列有10条未消费消息</strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.4k5fjvtukpe0.webp" alt="image"></p>
<p><strong>时间过去10秒，正常队列里面的消息由于没有被消费，消息进入死信队列</strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.5g2svti1sec0.webp" alt="image"></p>
<p><strong>消费者 C2 代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> frx</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 1.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2022/7/25  19:30</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer02</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//死信队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_QUEUE</span> <span class="operator">=</span> <span class="string">&quot;dead_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;等待接收死信消息...&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag, message) -&gt;&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;Consumer02接受的消息是：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(),<span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        channel.basicConsume(DEAD_QUEUE,<span class="literal">true</span>,deliverCallback,consumerTag -&gt; &#123;&#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>效果演示</strong></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.3a1tkaqx5jm0.webp" alt="image"></p>
<ul>
<li>控制台</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.2qvoqd9bcdc0.webp" alt="image"></p>
<h3 id="死信最大长度"><a href="#死信最大长度" class="headerlink" title="死信最大长度"></a>死信最大长度</h3><ol>
<li>消息生产者代码去掉 TTL 属性，<code>basicPublish</code> 的第三个参数改为 null</li>
</ol>
<figure class="highlight java"><figcaption><span>&#123;9,10,13&#125;</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer</span> &#123;</span><br><span class="line">    <span class="comment">//普通交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">NORMAL_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;normal_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//死信消息 设置ttl时间 live to time 单位是ms</span></span><br><span class="line">        <span class="comment">//AMQP.BasicProperties properties =</span></span><br><span class="line">        <span class="comment">//        new AMQP.BasicProperties().builder().expiration(&quot;10000&quot;).build();</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt;<span class="number">11</span> ; i++) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;info&quot;</span>+i;</span><br><span class="line">            channel.basicPublish(NORMAL_EXCHANGE,<span class="string">&quot;zhangsan&quot;</span>,<span class="literal">null</span>,message.getBytes());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li>C1 消费者修改以下代码(<strong>启动之后关闭该消费者 模拟其接收不到消息</strong>)</li>
</ol>
<figure class="highlight java"><figcaption><span>&#123;30&#125;</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer01</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//普通交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">NORMAL_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;normal_exchange&quot;</span>;</span><br><span class="line">    <span class="comment">//死信交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;dead_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//普通队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">NORMAL_QUEUE</span> <span class="operator">=</span> <span class="string">&quot;normal_queue&quot;</span>;</span><br><span class="line">    <span class="comment">//死信队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_QUEUE</span> <span class="operator">=</span> <span class="string">&quot;dead_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明死信和普通交换机，类型为direct</span></span><br><span class="line">        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);</span><br><span class="line">        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明普通队列</span></span><br><span class="line">        Map&lt;String,Object&gt; arguments = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        <span class="comment">//过期时间 10s 由生产者指定 更加灵活</span></span><br><span class="line">        <span class="comment">//arguments.put(&quot;x-message-ttl&quot;,10000);</span></span><br><span class="line">        <span class="comment">//正常的队列设置死信交换机</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-exchange&quot;</span>,DEAD_EXCHANGE);<span class="comment">//图中红箭头</span></span><br><span class="line">        <span class="comment">//设置死信routingKey</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-routing-key&quot;</span>,<span class="string">&quot;lisi&quot;</span>);</span><br><span class="line">        <span class="comment">//设置正常队列长度的限制，例如发送10个消息，6个为正常，4个为死信</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-max-length&quot;</span>,<span class="number">6</span>);</span><br><span class="line">        </span><br><span class="line">        channel.queueDeclare(NORMAL_QUEUE,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">false</span>,arguments);</span><br><span class="line">        <span class="comment">/////////////////////////////////////////////////////////////////////////</span></span><br><span class="line">        <span class="comment">//声明死信队列</span></span><br><span class="line">        channel.queueDeclare(DEAD_QUEUE,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//绑定普通的交换机与队列</span></span><br><span class="line">        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//绑定死信的交换机与死信的队列</span></span><br><span class="line">        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,<span class="string">&quot;lisi&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;等待接收消息...&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag,message) -&gt;&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;Consumer01接受的消息是：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(),<span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        channel.basicConsume(NORMAL_QUEUE,<span class="literal">true</span>,deliverCallback,consumerTag -&gt; &#123;&#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>::: tip 注意</p>
<p>因为参数改变了，所以需要把原先队列删除</p>
<p>:::</p>
<ol>
<li>C2 消费者代码不变</li>
</ol>
<ul>
<li>启动消费者C1，创建出队列，然后停止该 C1 的运行，启动生产者</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.6nv41w7ky0o0.webp" alt="image"></p>
<ul>
<li>启动 C2 消费者</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.3mg5ph9jr020.webp" alt="image"></p>
<ul>
<li>控制台</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.664h3njwl6w0.webp" alt="image"></p>
<h3 id="死信消息被拒"><a href="#死信消息被拒" class="headerlink" title="死信消息被拒"></a>死信消息被拒</h3><ol>
<li>消息生产者代码同上生产者一致</li>
<li>需求：消费者 C1 拒收消息 “info5”，开启手动应答</li>
</ol>
<p><strong>消费者C1</strong></p>
<figure class="highlight java"><figcaption><span>&#123;30,46-53,57&#125;</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer01</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//普通交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">NORMAL_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;normal_exchange&quot;</span>;</span><br><span class="line">    <span class="comment">//死信交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;dead_exchange&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//普通队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">NORMAL_QUEUE</span> <span class="operator">=</span> <span class="string">&quot;normal_queue&quot;</span>;</span><br><span class="line">    <span class="comment">//死信队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_QUEUE</span> <span class="operator">=</span> <span class="string">&quot;dead_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> ChannelUtils.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明死信和普通交换机，类型为direct</span></span><br><span class="line">        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);</span><br><span class="line">        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明普通队列</span></span><br><span class="line">        Map&lt;String,Object&gt; arguments = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        <span class="comment">//过期时间 10s 由生产者指定 更加灵活</span></span><br><span class="line">        <span class="comment">//arguments.put(&quot;x-message-ttl&quot;,10000);</span></span><br><span class="line">        <span class="comment">//正常的队列设置死信交换机</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-exchange&quot;</span>,DEAD_EXCHANGE);<span class="comment">//图中红箭头</span></span><br><span class="line">        <span class="comment">//设置死信routingKey</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-routing-key&quot;</span>,<span class="string">&quot;lisi&quot;</span>);</span><br><span class="line">        <span class="comment">//设置正常队列长度的限制，例如发送10个消息，6个为正常，4个为死信</span></span><br><span class="line">        <span class="comment">//arguments.put(&quot;x-max-length&quot;,6);</span></span><br><span class="line"></span><br><span class="line">        channel.queueDeclare(NORMAL_QUEUE,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">false</span>,arguments);</span><br><span class="line">        <span class="comment">/////////////////////////////////////////////////////////////////////////</span></span><br><span class="line">        <span class="comment">//声明死信队列</span></span><br><span class="line">        channel.queueDeclare(DEAD_QUEUE,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//绑定普通的交换机与队列</span></span><br><span class="line">        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,<span class="string">&quot;zhangsan&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//绑定死信的交换机与死信的队列</span></span><br><span class="line">        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,<span class="string">&quot;lisi&quot;</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;等待接收消息...&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">DeliverCallback</span> <span class="variable">deliverCallback</span> <span class="operator">=</span> (consumerTag,message) -&gt;&#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">            <span class="keyword">if</span>(msg.equals(<span class="string">&quot;info5&quot;</span>))&#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;Consumer01接受的消息是：&quot;</span>+msg+<span class="string">&quot;： 此消息是被C1拒绝的&quot;</span>);</span><br><span class="line">                <span class="comment">//requeue 设置为 false 代表拒绝重新入队 该队列如果配置了死信交换机将发送到死信队列中</span></span><br><span class="line">                channel.basicReject(message.getEnvelope().getDeliveryTag(), <span class="literal">false</span>);</span><br><span class="line">            &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;Consumer01接受的消息是：&quot;</span>+msg);</span><br><span class="line">                channel.basicAck(message.getEnvelope().getDeliveryTag(), <span class="literal">false</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//开启手动应答，也就是关闭手动应答</span></span><br><span class="line">        channel.basicConsume(NORMAL_QUEUE,<span class="literal">false</span>,deliverCallback,consumerTag -&gt; &#123;&#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>开启消费者C1，创建出队列，然后停止该 C1 的运行，启动生产者</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.ncokzmns2t.webp" alt="image"></p>
<ul>
<li>启动消费者 C1 等待 10 秒之后，再启动消费者 C2</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.1xxchsmgsgdc.webp" alt="image"></p>
<ul>
<li>C1控制台</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.5zgbkg8gij80.webp" alt="image"></p>
<ul>
<li>C2控制台</li>
</ul>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.783con5n7f40.webp" alt="image"></p>
<h1 id="延迟队列"><a href="#延迟队列" class="headerlink" title="延迟队列"></a>延迟队列</h1><h2 id="延迟队列介绍"><a href="#延迟队列介绍" class="headerlink" title="延迟队列介绍"></a>延迟队列介绍</h2><p>延时队列,队列内部是有序的，最重要的特性就体现在它的延时属性上，延时队列中的元素是希望 在指定时间到了以后或之前取出和处理，简单来说，延时队列就是用来存放需要在指定时间被处理的 元素的队列。</p>
<ol>
<li>订单在十分钟之内未支付则自动取消</li>
<li>新创建的店铺，如果在十天内都没有上传过商品，则自动发送消息提醒</li>
<li>用户注册成功后，如果三天内没有登陆则进行短信提醒</li>
<li>用户发起退款，如果三天内没有得到处理则通知相关运营人员</li>
<li>预定会议后，需要在预定的时间点前十分钟通知各个与会人员参加会议</li>
</ol>
<p>这些场景都有一个特点，需要在某个事件发生之后或者之前的指定时间点完成某一项任务，如： 发生订单生成事件，在十分钟之后检查该订单支付状态，然后将未支付的订单进行关闭；那我们一直轮询数据，每秒查一次，取出需要被处理的数据，然后处理不就完事了吗？</p>
<p>如果数据量比较少，确实可以这样做，比如：对于「如果账单一周内未支付则进行自动结算」这样的需求， 如果对于时间不是严格限制，而是宽松意义上的一周，那么每天晚上跑个定时任务检查一下所有未支付的账单，确实也是一个可行的方案。但对于数据量比较大，并且时效性较强的场景，如：「订单十分钟内未支付则关闭」，短期内未支付的订单数据可能会有很多，活动期间甚至会达到百万甚至千万级别，对这么庞大的数据量仍旧使用轮询的方式显然是不可取的，很可能在一秒内无法完成所有订单的检查，同时会给数据库带来很大压力，无法满足业务要求而且性能低下。</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230530185309579.png" alt="image-20230530185309579"></p>
<h2 id="TTL的两种设置"><a href="#TTL的两种设置" class="headerlink" title="TTL的两种设置"></a>TTL的两种设置</h2><p>TTL 是什么呢？TTL 是 RabbitMQ 中一个消息或者队列的属性，表明一条消息或者该队列中的所有消息的最大存活时间，单位是毫秒。</p>
<p>换句话说，如果一条消息设置了 TTL 属性或者进入了设置 TTL 属性的队列，那么这条消息如果在 TTL 设置的时间内没有被消费，则会成为「死信」。如果同时配置了队列的 TTL 和消息的 TTL，那么较小的那个值将会被使用，有两种方式设置 TTL。</p>
<p><strong>队列设置 TTL</strong></p>
<p>在创建队列的时候设置队列的 x-message-ttl 属性</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;String, Object&gt; params = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">params.put(<span class="string">&quot;x-message-ttl&quot;</span>,<span class="number">5000</span>);</span><br><span class="line"><span class="keyword">return</span> QueueBuilder.durable(<span class="string">&quot;QA&quot;</span>).withArguments(args).build(); <span class="comment">// QA 队列的最大存活时间位 5000 毫秒</span></span><br></pre></td></tr></table></figure>
<p><strong>消息设置 TTL</strong></p>
<p>针对每条消息设置 TTL</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">rabbitTemplate.converAndSend(<span class="string">&quot;X&quot;</span>,<span class="string">&quot;XC&quot;</span>,message,correlationData -&gt; &#123;</span><br><span class="line">    correlationData.getMessageProperties().setExpiration(<span class="string">&quot;5000&quot;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>两个代码块来自下方的案例</p>
<p><strong>两者区别</strong></p>
<p>如果设置了队列的 TTL 属性，那么一旦消息过期，就会被队列丢弃(如果配置了死信队列被丢到死信队列中)，而第二种方式，消息即使过期，也不一定会被马上丢弃，因为消息是否过期是在即将投递到消费者之前判定的，如果当前队列有严重的消息积压情况，则已过期的消息也许还能存活较长时间，具体看下方案例。</p>
<p>另外，还需要注意的一点是，如果不设置 TTL，表示消息永远不会过期，如果将 TTL 设置为 0，则表示除非此时可以直接投递该消息到消费者，否则该消息将会被丢弃</p>
<h2 id="SpringBoot中整合RabbitMQ"><a href="#SpringBoot中整合RabbitMQ" class="headerlink" title="SpringBoot中整合RabbitMQ"></a>SpringBoot中整合RabbitMQ</h2><blockquote>
<p><strong>使用<a href="https://www.naste.top:18083/">小飞代码生成器</a>快速生成SpringBoot项目</strong></p>
</blockquote>
<h3 id="依赖"><a href="#依赖" class="headerlink" title="依赖"></a>依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--RabbitMQ-SpringBoot 依赖--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-amqp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="yml配置"><a href="#yml配置" class="headerlink" title="yml配置"></a>yml配置</h3><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="number">192.168</span><span class="number">.40</span><span class="number">.168</span></span><br><span class="line">    <span class="attr">port:</span> <span class="number">5672</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">guest</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">guest</span></span><br></pre></td></tr></table></figure>
<h2 id="队列TTL—SpringBoot"><a href="#队列TTL—SpringBoot" class="headerlink" title="队列TTL—SpringBoot"></a>队列TTL—SpringBoot</h2><h3 id="代码架构图"><a href="#代码架构图" class="headerlink" title="代码架构图"></a>代码架构图</h3><p>创建两个队列 QA 和 QB，两个队列的 TTL 分别设置为 10S 和 40S，然后再创建一个交换机 X 和死信交换机 Y，它们的类型都是 direct，创建一个死信队列 QD，它们的绑定关系如下：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.6ipia9redgw0.webp" alt="image"></p>
<p>原先配置队列信息，写在了生产者和消费者代码中，现在可写在配置类中，生产者只发消息，消费者只接受消息</p>
<h3 id="TTL配置"><a href="#TTL配置" class="headerlink" title="TTL配置"></a>TTL配置</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.amqp.core.*;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * TTL配置类代码</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TtlQueueConfig</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//普通交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">X_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;X&quot;</span>;</span><br><span class="line">    <span class="comment">//死信交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">Y_DEAD_LETTER_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;Y&quot;</span>;</span><br><span class="line">    <span class="comment">//普通队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_A</span> <span class="operator">=</span> <span class="string">&quot;QA&quot;</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_B</span> <span class="operator">=</span> <span class="string">&quot;QB&quot;</span>;</span><br><span class="line">    <span class="comment">//死信队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DEAD_LETTER_QUEUE</span> <span class="operator">=</span> <span class="string">&quot;QD&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 声明xExchange  别名</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean(&quot;xExchange&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> DirectExchange <span class="title function_">xExchange</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">DirectExchange</span>(X_EXCHANGE);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 声明yExchange 别名</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean(&quot;yExchange&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> DirectExchange <span class="title function_">yExchange</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">DirectExchange</span>(Y_DEAD_LETTER_EXCHANGE);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 声明普通队列  要有ttl 为10s</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean(&quot;queueA&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">queueA</span><span class="params">()</span> &#123;</span><br><span class="line">        Map&lt;String, Object&gt; arguments = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;(<span class="number">3</span>);</span><br><span class="line">        <span class="comment">//设置死信交换机</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-exchange&quot;</span>, Y_DEAD_LETTER_EXCHANGE);</span><br><span class="line">        <span class="comment">//设置死信RoutingKey</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-routing-key&quot;</span>, <span class="string">&quot;YD&quot;</span>);</span><br><span class="line">        <span class="comment">//设置TTL 10s 单位是ms</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-message-ttl&quot;</span>, <span class="number">10000</span>);</span><br><span class="line">        <span class="keyword">return</span> QueueBuilder.durable(QUEUE_A).withArguments(arguments).build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 声明普通队列  要有ttl 为40s</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean(&quot;queueB&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">queueB</span><span class="params">()</span> &#123;</span><br><span class="line">        Map&lt;String, Object&gt; arguments = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;(<span class="number">3</span>);</span><br><span class="line">        <span class="comment">//设置死信交换机</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-exchange&quot;</span>, Y_DEAD_LETTER_EXCHANGE);</span><br><span class="line">        <span class="comment">//设置死信RoutingKey</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-routing-key&quot;</span>, <span class="string">&quot;YD&quot;</span>);</span><br><span class="line">        <span class="comment">//设置TTL 10s 单位是ms</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-message-ttl&quot;</span>, <span class="number">40000</span>);</span><br><span class="line">        <span class="keyword">return</span> QueueBuilder.durable(QUEUE_B).withArguments(arguments).build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 声明死信队列  要有ttl 为40s</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean(&quot;queueD&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">queueD</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> QueueBuilder.durable(DEAD_LETTER_QUEUE).build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 声明队列 QA 绑定 X 交换机</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">queueABindingX</span><span class="params">(<span class="meta">@Qualifier(&quot;queueA&quot;)</span> Queue queueA,</span></span><br><span class="line"><span class="params">                                  <span class="meta">@Qualifier(&quot;xExchange&quot;)</span> DirectExchange xExchange)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(queueA).to(xExchange).with(<span class="string">&quot;XA&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 声明队列 QB 绑定 X 交换机</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">queueBBindingX</span><span class="params">(<span class="meta">@Qualifier(&quot;queueB&quot;)</span> Queue queueB,</span></span><br><span class="line"><span class="params">                                  <span class="meta">@Qualifier(&quot;xExchange&quot;)</span> DirectExchange xExchange)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(queueB).to(xExchange).with(<span class="string">&quot;XB&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 声明队列 QD 绑定 Y 交换机</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">queueDBindingY</span><span class="params">(<span class="meta">@Qualifier(&quot;queueD&quot;)</span> Queue queueD,</span></span><br><span class="line"><span class="params">                                  <span class="meta">@Qualifier(&quot;yExchange&quot;)</span> DirectExchange yExchange)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(queueD).to(yExchange).with(<span class="string">&quot;YD&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="生产者-8"><a href="#生产者-8" class="headerlink" title="生产者"></a>生产者</h3><p><strong>Controller层接收参数，将接收的参数信息放入到RabbitMQ中</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> io.swagger.annotations.Api;</span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.amqp.rabbit.core.RabbitTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.GetMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.PathVariable;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RestController;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 发送消息</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Api(tags = &quot;发送消息&quot;)</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;ttl&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SendMessageController</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 开始发消息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/sendMsg/&#123;message&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sendMsg</span><span class="params">(<span class="meta">@PathVariable(&quot;message&quot;)</span> String message)</span> &#123;</span><br><span class="line">        log.info(<span class="string">&quot;当前时间:&#123;&#125;,发送一条信息给两个TTL队列：&#123;&#125;&quot;</span>, <span class="keyword">new</span> <span class="title class_">Date</span>().toString(), message);</span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;X&quot;</span>, <span class="string">&quot;XA&quot;</span>, <span class="string">&quot;消息来自ttl为10s的队列:&quot;</span> + message);</span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;X&quot;</span>, <span class="string">&quot;XB&quot;</span>, <span class="string">&quot;消息来自ttl为40s的队列:&quot;</span> + message);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h3><p>发起请求：<a target="_blank" rel="noopener" href="http://localhost:8088/ttl/sendMsg/哈哈哈1">http://localhost:8088/ttl/sendMsg/哈哈哈1</a></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image-20230530202305866.png" alt="image-20230530202305866"></p>
<p>第一条消息在 10S 后变成了死信消息，然后被消费者消费掉，第二条消息在 40S 之后变成了死信消息， 然后被消费掉，这样一个延时队列就打造完成了。</p>
<p>不过，如果这样使用的话，岂不是每增加一个新的时间需求，就要新增一个队列，这里只有 10S 和 40S 两个时间选项，如果需要一个小时后处理，那么就需要增加 TTL 为一个小时的队列，如果是预定会议室然后提前通知这样的场景，岂不是要增加无数个队列才能满足需求？</p>
<h2 id="延时队列TTL优化"><a href="#延时队列TTL优化" class="headerlink" title="延时队列TTL优化"></a>延时队列TTL优化</h2><p>在这里新增了一个队列 QC，该队列不设置 TTL 时间，根据前端的请求确定 TTL 时间，绑定关系如下：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.267zky9xj8dc.webp" alt="image"></p>
<h3 id="配置类代码"><a href="#配置类代码" class="headerlink" title="配置类代码"></a>配置类代码</h3><p><strong>新增一个配置文件类，用于新增队列 QC，也可以放在上方的配置文件类里</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.amqp.core.*;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MsgTtlQueueConfig</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//普通队列的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_C</span> <span class="operator">=</span> <span class="string">&quot;QC&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//死信交换机的名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String Y_DEAD_LETTER_EXCHANGE=<span class="string">&quot;Y&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//声明QC</span></span><br><span class="line">    <span class="meta">@Bean(&quot;queueC&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">QueueC</span><span class="params">()</span>&#123;</span><br><span class="line">        Map&lt;String,Object&gt; arguments = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;(<span class="number">3</span>);</span><br><span class="line">        <span class="comment">//设置死信交换机</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-exchange&quot;</span>,Y_DEAD_LETTER_EXCHANGE);</span><br><span class="line">        <span class="comment">//设置死信RoutingKey</span></span><br><span class="line">        arguments.put(<span class="string">&quot;x-dead-letter-routing-key&quot;</span>,<span class="string">&quot;XC&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> QueueBuilder.durable(QUEUE_C).withArguments(arguments).build();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//声明队列 QC 绑定 X 交换机</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">queueCBindingX</span><span class="params">(<span class="meta">@Qualifier(&quot;queueC&quot;)</span> Queue queueC,</span></span><br><span class="line"><span class="params">                                  <span class="meta">@Qualifier(&quot;xExchange&quot;)</span> DirectExchange xExchange)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(queueC).to(xExchange).with(<span class="string">&quot;XC&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="生产者-9"><a href="#生产者-9" class="headerlink" title="生产者"></a>生产者</h3><p><strong>Controller 新增方法：该方法接收的请求要带有 TTL 时间</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xiaofei.rabbit.controller;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> io.swagger.annotations.Api;</span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.amqp.rabbit.core.RabbitTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.GetMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.PathVariable;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RestController;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 发送消息</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Api(tags = &quot;发送消息&quot;)</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;ttl&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SendMessageController</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 开始发消息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/sendMsg/&#123;message&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sendMsg</span><span class="params">(<span class="meta">@PathVariable(&quot;message&quot;)</span> String message)</span> &#123;</span><br><span class="line">        log.info(<span class="string">&quot;当前时间:&#123;&#125;,发送一条信息给两个TTL队列：&#123;&#125;&quot;</span>, <span class="keyword">new</span> <span class="title class_">Date</span>().toString(), message);</span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;X&quot;</span>, <span class="string">&quot;XA&quot;</span>, <span class="string">&quot;消息来自ttl为10s的队列:&quot;</span> + message);</span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;X&quot;</span>, <span class="string">&quot;XB&quot;</span>, <span class="string">&quot;消息来自ttl为40s的队列:&quot;</span> + message);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 开始发消息 发TTL</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/sendExpirationMsg/&#123;message&#125;/&#123;ttlTime&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sendMsg</span><span class="params">(<span class="meta">@PathVariable(&quot;message&quot;)</span> String message,</span></span><br><span class="line"><span class="params">                        <span class="meta">@PathVariable(&quot;ttlTime&quot;)</span> String ttlTime)</span> &#123;</span><br><span class="line">        log.info(<span class="string">&quot;当前时间:&#123;&#125;,发送一条时长是&#123;&#125;毫秒TTL信息给队列QC：&#123;&#125;&quot;</span>,</span><br><span class="line">                <span class="keyword">new</span> <span class="title class_">Date</span>().toString(), ttlTime, message);</span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;X&quot;</span>, <span class="string">&quot;XC&quot;</span>, message, msg -&gt; &#123;</span><br><span class="line">            <span class="comment">//发送消息的时候的延迟时长</span></span><br><span class="line">            msg.getMessageProperties().setExpiration(ttlTime);</span><br><span class="line">            <span class="keyword">return</span> msg;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="测试-1"><a href="#测试-1" class="headerlink" title="测试"></a>测试</h3><p>发送请求</p>
<ul>
<li><a target="_blank" rel="noopener" href="http://localhost:8088/ttl/sendExpirationMsg/你好1/20000">http://localhost:8088/ttl/sendExpirationMsg/你好1/20000</a></li>
<li><a target="_blank" rel="noopener" href="http://localhost:8088/ttl/sendExpirationMsg/你好2/2000">http://localhost:8088/ttl/sendExpirationMsg/你好2/2000</a></li>
</ul>
<blockquote>
<p><strong>出现问题</strong>:</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/1658765665496.39yyrmljat80.webp" alt="1658765665496"></p>
</blockquote>
<p>看起来似乎没什么问题，但是在最开始的时候，就介绍过如果使用在消息属性上设置 TTL 的方式，消息可能并不会按时「死亡」</p>
<blockquote>
<p>因为 RabbitMQ 只会检查第一个消息是否过期，如果过期则丢到死信队列， 如果第一个消息的延时时长很长，而第二个消息的延时时长很短，第二个消息并不会优先得到执行</p>
</blockquote>
<p>这也就是为什么如图的时间：你好 2 延时 2 秒，却后执行，还要等待你好 1 消费后再执行你好2</p>
<h2 id="Rabbitmq插件实现延迟队列（后续补充或修改）"><a href="#Rabbitmq插件实现延迟队列（后续补充或修改）" class="headerlink" title="Rabbitmq插件实现延迟队列（后续补充或修改）"></a>Rabbitmq插件实现延迟队列（后续补充或修改）</h2><p>上文中提到的问题，确实是一个问题，如果不能实现在消息粒度上的 TTL，并使其在设置的 TTL 时间及时死亡，就无法设计成一个通用的延时队列。那如何解决呢，接下来我们就去解决该问题。</p>
<p><strong>安装延时队列插件</strong></p>
<p>可去<a target="_blank" rel="noopener" href="https://www.rabbitmq.com/community-plugins.html">官网下载</a>找到 <strong>rabbitmq_delayed_message_exchange</strong> 插件，放置到 RabbitMQ 的插件目录。</p>
<p>因为官网也是跳转去该插件的 GitHub 地址进行下载：<a target="_blank" rel="noopener" href="https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/releases">点击跳转</a></p>
<p>打开 Linux，用 <code>Xftp</code> 将插件放到 RabbitMQ 的<mark>安装目录</mark>下的 plgins 目录，</p>
<p>RabbitMQ 与其 plgins 目录默认分别位于</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># RabbitMQ 安装目录</span></span><br><span class="line"><span class="built_in">cd</span> /usr/lib/rabbitmq/lib/rabbitmq_server-3.8.8   </span><br><span class="line"><span class="comment"># RabbitMQ 的 plgins 所在目录</span></span><br><span class="line"><span class="built_in">cd</span> /usr/lib/rabbitmq/lib/rabbitmq_server-3.8.8/plugins</span><br></pre></td></tr></table></figure>
<p>其中我的版本是 <code>/rabbitmq_server-3.8.8</code></p>
<p>进入目录后执行下面命令让该插件生效，然后重启 RabbitMQ</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 安装</span></span><br><span class="line">rabbitmq-plugins <span class="built_in">enable</span> rabbitmq_delayed_message_exchange</span><br><span class="line"><span class="comment"># 重启服务</span></span><br><span class="line">systemctl restart rabbitmq-server</span><br></pre></td></tr></table></figure>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">[root@master plugins]<span class="comment"># rabbitmq-plugins enable rabbitmq_delayed_message_exchange</span></span><br><span class="line">Enabling plugins on node rabbit@master:</span><br><span class="line">rabbitmq_delayed_message_exchange</span><br><span class="line">The following plugins have been configured:</span><br><span class="line">  rabbitmq_delayed_message_exchange</span><br><span class="line">  rabbitmq_management</span><br><span class="line">  rabbitmq_management_agent</span><br><span class="line">  rabbitmq_web_dispatch</span><br><span class="line">Applying plugin configuration to rabbit@master...</span><br><span class="line">The following plugins have been enabled:</span><br><span class="line">  rabbitmq_delayed_message_exchange</span><br><span class="line"></span><br><span class="line">started 1 plugins.</span><br><span class="line">[root@master plugins]<span class="comment"># systemctl restart rabbitmq-server</span></span><br></pre></td></tr></table></figure>
<p>::: tip 解释</p>
<p>安装命令不能出现插件版本和后缀，如 <code>rabbitmq-plugins enable rabbitmq_delayed_message_exchange-3.8.0.ez</code> 会报错</p>
<p>必须是 <code>rabbitmq-plugins enable rabbitmq_delayed_message_exchange</code>，后面不允许填入版本和文件后缀</p>
<p>:::</p>
<p>打开 Web 界面，查看交换机的新增功能列表，如果多出了如图所示，代表成功添加插件</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.3nqc69j0pws0.webp" alt="image"></p>
<h2 id="插件实战"><a href="#插件实战" class="headerlink" title="插件实战"></a>插件实战</h2><p>在这里新增了一个队列 delayed.queue，一个自定义交换机 delayed.exchange，绑定关系如下:</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.1tla4z5g4yps.webp" alt="image"></p>
<h3 id="配置类代码-1"><a href="#配置类代码-1" class="headerlink" title="配置类代码"></a>配置类代码</h3><p>新增一个配置类 <code>DelayedQueueConfig</code>，也可以放在原来的配置文件里，代码里使用了 <code>CustomExchange</code> 类，通过参数来自定义一个类型(direct、topic等)</p>
<p>在我们自定义的交换机中，这是一种新的交换类型，该类型消息支持延迟投递机制消息传递后并不会立即投递到目标队列中，而是存储在 mnesia(一个分布式数据系统)表中，当达到投递时间时，才投递到目标队列中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DelayedQueueConfig</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//交换机</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DELAYED_EXCHANGE_NAME</span> <span class="operator">=</span> <span class="string">&quot;delayed.exchange&quot;</span>;</span><br><span class="line">    <span class="comment">//队列</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DELAYED_QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;delayed.queue&quot;</span>;</span><br><span class="line">    <span class="comment">//routingKey</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DELAYED_ROUTING_KEY</span> <span class="operator">=</span> <span class="string">&quot;delayed.routingkey&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">delayedQueue</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Queue</span>(DELAYED_QUEUE_NAME);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//声明交换机,基于插件的交换机</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> CustomExchange <span class="title function_">delayedExchange</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">        Map&lt;String,Object&gt; arguments = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        arguments.put(<span class="string">&quot;x-delayed-type&quot;</span>,<span class="string">&quot;direct&quot;</span>);</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 1.交换机的名称</span></span><br><span class="line"><span class="comment">         * 2.交换机的类型 x-delayed-message</span></span><br><span class="line"><span class="comment">         * 3.是否需要持久化</span></span><br><span class="line"><span class="comment">         * 4.是否需要自动删除</span></span><br><span class="line"><span class="comment">         * 5.其他的参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">CustomExchange</span>(DELAYED_EXCHANGE_NAME,<span class="string">&quot;x-delayed-message&quot;</span>,</span><br><span class="line">                <span class="literal">true</span>,<span class="literal">false</span>,arguments);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//绑定</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">delayedQueueBindingDelayedExchange</span><span class="params">(</span></span><br><span class="line"><span class="params">            <span class="meta">@Qualifier(&quot;delayedQueue&quot;)</span> Queue delayedQueue,</span></span><br><span class="line"><span class="params">            <span class="meta">@Qualifier(&quot;delayedExchange&quot;)</span>CustomExchange delayedExchange)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(delayedQueue).to(delayedExchange)</span><br><span class="line">                .with(DELAYED_ROUTING_KEY).noargs();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>生产者代码</strong></p>
<p>在 controller 里新增一个方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//开始发消息，基于插件的 消息及 延迟的时间</span></span><br><span class="line"><span class="meta">@GetMapping(&quot;/sendDelayMsg/&#123;message&#125;/&#123;delayTime&#125;&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sendMsg</span><span class="params">(<span class="meta">@PathVariable(&quot;message&quot;)</span> String message,</span></span><br><span class="line"><span class="params">                    <span class="meta">@PathVariable(&quot;delayTime&quot;)</span> Integer delayTime)</span>&#123;</span><br><span class="line">    log.info(<span class="string">&quot;当前时间:&#123;&#125;,发送一条时长是&#123;&#125;毫秒TTL信息给延迟队列delayed.queue：&#123;&#125;&quot;</span>,</span><br><span class="line">            <span class="keyword">new</span> <span class="title class_">Date</span>().toString(),delayTime,message);</span><br><span class="line"></span><br><span class="line">    rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME,</span><br><span class="line">            DelayedQueueConfig.DELAYED_ROUTING_KEY,message, msg -&gt; &#123;</span><br><span class="line">        <span class="comment">//发送消息的时候的延迟时长 单位ms</span></span><br><span class="line">        msg.getMessageProperties().setDelay(delayTime);</span><br><span class="line">        <span class="keyword">return</span> msg;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>消费者代码</strong></p>
<p>监听延时队列，如果有消息进入该队列，则打印到控制台</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DelayQueueConsumer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(queues = DelayedQueueConfig.DELAYED_QUEUE_NAME)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">receiveDelayQueue</span><span class="params">(Message message)</span>&#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody());</span><br><span class="line">        log.info(<span class="string">&quot;当前时间：&#123;&#125;,收到延时队列的消息：&#123;&#125;&quot;</span>, <span class="keyword">new</span> <span class="title class_">Date</span>().toString(), msg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a target="_blank" rel="noopener" href="http://localhost:8088/ttl/sendDelayMsg/hello1/20000">http://localhost:8088/ttl/sendDelayMsg/hello1/20000</a></p>
<p><a target="_blank" rel="noopener" href="http://localhost:8088/ttl/sendDelayMsg/hello2/2000">http://localhost:8088/ttl/sendDelayMsg/hello2/2000</a></p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/images/image.17h77dwilchs.webp" alt="image"></p>
<p>可以看到哪怕 hello1 需要20秒再进入延时队列，hello2 2 秒后直接进入延时队列，无需等待 hello1</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>延时队列在需要延时处理的场景下非常有用，使用 RabbitMQ 来实现延时队列可以很好的利用 RabbitMQ 的特性，如：消息可靠发送、消息可靠投递、死信队列来保障消息至少被消费一次以及未被正确处理的消息不会被丢弃。另外，通过 RabbitMQ 集群的特性，可以很好的解决单点故障问题，不会因为单个节点挂掉导致延时队列不可用或者消息丢失。</p>
<p>当然，延时队列还有很多其它选择，比如利用 Java 的 DelayQueue，利用 Redis 的 zset，利用 Quartz 或者利用 kafka 的时间轮，这些方式各有特点,看需要适用的场景。</p>
<h1 id="发布确认高级"><a href="#发布确认高级" class="headerlink" title="发布确认高级"></a>发布确认高级</h1><h2 id="发布确认SpringBoot版本"><a href="#发布确认SpringBoot版本" class="headerlink" title="发布确认SpringBoot版本"></a>发布确认SpringBoot版本</h2><h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><h3 id="实战"><a href="#实战" class="headerlink" title="实战"></a>实战</h3><h3 id="添加配置类"><a href="#添加配置类" class="headerlink" title="添加配置类"></a>添加配置类</h3><h3 id="消息生产者"><a href="#消息生产者" class="headerlink" title="消息生产者"></a>消息生产者</h3><h3 id="消息消费者"><a href="#消息消费者" class="headerlink" title="消息消费者"></a>消息消费者</h3><h3 id="消息生产者发布消息后的回调接口"><a href="#消息生产者发布消息后的回调接口" class="headerlink" title="消息生产者发布消息后的回调接口"></a>消息生产者发布消息后的回调接口</h3><h2 id="回退消息"><a href="#回退消息" class="headerlink" title="回退消息"></a>回退消息</h2><h3 id="介绍-1"><a href="#介绍-1" class="headerlink" title="介绍"></a>介绍</h3><h2 id="实战-1"><a href="#实战-1" class="headerlink" title="实战"></a>实战</h2><h3 id="修改配置文件"><a href="#修改配置文件" class="headerlink" title="修改配置文件"></a>修改配置文件</h3><h3 id="修改回调接口"><a href="#修改回调接口" class="headerlink" title="修改回调接口"></a>修改回调接口</h3><h2 id="备份交换机"><a href="#备份交换机" class="headerlink" title="备份交换机"></a>备份交换机</h2><h3 id="介绍-2"><a href="#介绍-2" class="headerlink" title="介绍"></a>介绍</h3><h3 id="实战-2"><a href="#实战-2" class="headerlink" title="实战"></a>实战</h3><h3 id="修改高级确认发布-配置类"><a href="#修改高级确认发布-配置类" class="headerlink" title="修改高级确认发布 配置类"></a>修改高级确认发布 配置类</h3><h3 id="报警消费者"><a href="#报警消费者" class="headerlink" title="报警消费者"></a>报警消费者</h3><h1 id="RabbitMQ其他知识点"><a href="#RabbitMQ其他知识点" class="headerlink" title="RabbitMQ其他知识点"></a>RabbitMQ其他知识点</h1><h2 id="幂等性"><a href="#幂等性" class="headerlink" title="幂等性"></a>幂等性</h2><h3 id="概念-1"><a href="#概念-1" class="headerlink" title="概念"></a>概念</h3><h3 id="消息重复消费"><a href="#消息重复消费" class="headerlink" title="消息重复消费"></a>消息重复消费</h3><h3 id="解决思路"><a href="#解决思路" class="headerlink" title="解决思路"></a>解决思路</h3><h3 id="消费端的幂等性保障"><a href="#消费端的幂等性保障" class="headerlink" title="消费端的幂等性保障"></a>消费端的幂等性保障</h3><h2 id="优先级队列"><a href="#优先级队列" class="headerlink" title="优先级队列"></a>优先级队列</h2><h3 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h3><h3 id="添加方法"><a href="#添加方法" class="headerlink" title="添加方法"></a>添加方法</h3><h2 id="实战-3"><a href="#实战-3" class="headerlink" title="实战"></a>实战</h2><h3 id="生产者代码"><a href="#生产者代码" class="headerlink" title="生产者代码"></a>生产者代码</h3><h3 id="消费者代码"><a href="#消费者代码" class="headerlink" title="消费者代码"></a>消费者代码</h3><h2 id="惰性队列"><a href="#惰性队列" class="headerlink" title="惰性队列"></a>惰性队列</h2><h3 id="使用场景-1"><a href="#使用场景-1" class="headerlink" title="使用场景"></a>使用场景</h3><h3 id="两种模式"><a href="#两种模式" class="headerlink" title="两种模式"></a>两种模式</h3><h3 id="内存开销对比"><a href="#内存开销对比" class="headerlink" title="内存开销对比"></a>内存开销对比</h3><blockquote>
<p><strong>死信队列、延迟队列、发布确认高级、RabbitmQ其他知识点等后续使用到进行补充</strong></p>
</blockquote>
</article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>RabbitMQ</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="https://www.naste.top:1024/posts/3041119952.html">https://www.naste.top:1024/posts/3041119952.html</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>XiaoFei🥝</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2023-05-21</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2024-04-26</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>Java</a><a class="post-meta__tags" href="/tags/SpringBoot/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>SpringBoot</a><a class="post-meta__tags" href="/tags/RabbitMQ/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>RabbitMQ</a></div></div><link rel="stylesheet" href="/css/coin.css" media="defer" onload="this.media='all'"/><div class="post-reward"><button class="tip-button reward-button"><span class="tip-button__text">投喂作者</span><div class="coin-wrapper"><div class="coin"><div class="coin__middle"></div><div class="coin__back"></div><div class="coin__front"></div></div></div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://www.naste.top:9000/images/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://www.naste.top:9000/images/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></button></div><audio id="coinAudio" src="https://npm.elemecdn.com/akilar-candyassets@1.0.36/audio/aowu.m4a"></audio><script defer="defer" src="/js/coin.js"></script><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/3353504920.html"><img class="prev-cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743769.webp" onerror="onerror=null;src='/assets/r2.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">设计模式-策略模式</div></div></a></div><div class="next-post pull-right"><a href="/posts/1455011995.html"><img class="next-cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678672759.webp" onerror="onerror=null;src='/assets/r2.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">使用JavaScript修改网页任意元素的文本内容</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/4265763703.html" title="使用Spring Session解决分布式Session共享问题"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1671882661.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">使用Spring Session解决分布式Session共享问题</div></div></a></div><div><a href="/posts/1154747761.html" title="代码生成器项目解读"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678368249.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">代码生成器项目解读</div></div></a></div><div><a href="/posts/2510331546.html" title="SpringBoot3响应式编程"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1671882662.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">SpringBoot3响应式编程</div></div></a></div><div><a href="/posts/3528284937.html" title="SpringBoot自定义注解使用"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1671882685.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">SpringBoot自定义注解使用</div></div></a></div><div><a href="/posts/1864766114.html" title="SpringBoot"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743771.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">SpringBoot</div></div></a></div><div><a href="/posts/1575856937.html" title="SpringBoot添加对LocalDateTime序列化"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1671882661.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">SpringBoot添加对LocalDateTime序列化</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><svg class="meta_icon" style="width:22px;height:22px;position:relative;top:5px"><use xlink:href="#icon-mulu1"></use></svg><span style="font-weight:bold">目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%9B%AE%E5%BD%95"><span class="toc-text">目录</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%BF%85%E8%AF%BB"><span class="toc-text">必读</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%AE%89%E8%A3%85"><span class="toc-text">安装</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Docker%E5%AE%89%E8%A3%85"><span class="toc-text">Docker安装</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%95%E6%9C%BA%E9%83%A8%E7%BD%B2"><span class="toc-text">单机部署</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#MQ%E6%A6%82%E5%BF%B5"><span class="toc-text">MQ概念</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFMQ"><span class="toc-text">什么是MQ</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E7%94%A8MQ"><span class="toc-text">为什么要用MQ</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#MQ%E5%88%86%E7%B1%BB"><span class="toc-text">MQ分类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#MQ%E9%80%89%E6%8B%A9"><span class="toc-text">MQ选择</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#RabbitMQ%E7%9B%B8%E5%85%B3%E6%A6%82%E5%BF%B5"><span class="toc-text">RabbitMQ相关概念</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#RabbitMQ%E6%A6%82%E5%BF%B5"><span class="toc-text">RabbitMQ概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RabbitMQ%E5%9B%9B%E5%A4%A7%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5"><span class="toc-text">RabbitMQ四大核心概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RabbitMQ%E6%A0%B8%E5%BF%83%E9%83%A8%E5%88%86"><span class="toc-text">RabbitMQ核心部分</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RabbitMQ%E5%90%8D%E8%AF%8D%E4%BB%8B%E7%BB%8D"><span class="toc-text">RabbitMQ名词介绍</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-text">代码工具类</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#RabbitMQ%E8%BF%9E%E6%8E%A5%E4%BF%A1%E9%81%93%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-text">RabbitMQ连接信道工具类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%9D%A1%E7%9C%A0%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-text">睡眠工具类</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%A5%E9%97%A8%E6%A1%88%E4%BE%8B"><span class="toc-text">入门案例</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Hello-World"><span class="toc-text">Hello World</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81"><span class="toc-text">代码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#maven%E4%BE%9D%E8%B5%96"><span class="toc-text">maven依赖</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%85"><span class="toc-text">消费者</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Work-Queues"><span class="toc-text">Work Queues</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BD%AE%E8%AF%A2%E6%B6%88%E8%B4%B9"><span class="toc-text">轮询消费</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#web%E9%A1%B5%E9%9D%A2%E6%B7%BB%E5%8A%A0%E9%98%9F%E5%88%97"><span class="toc-text">web页面添加队列</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B6%88%E6%81%AF%E5%BA%94%E7%AD%94%E5%92%8C%E5%8F%91%E5%B8%83"><span class="toc-text">消息应答和发布</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B6%88%E6%81%AF%E5%BA%94%E7%AD%94"><span class="toc-text">消息应答</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A6%82%E5%BF%B5"><span class="toc-text">概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%8A%A8%E5%BA%94%E7%AD%94%EF%BC%88%E6%97%A0%E9%9C%80%E8%AE%BE%E7%BD%AE%EF%BC%89"><span class="toc-text">自动应答（无需设置）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%8B%E5%8A%A8%E5%BA%94%E7%AD%94%E6%96%B9%E6%B3%95%E5%8F%8A%E5%8F%82%E6%95%B0%E8%A7%A3%E9%87%8A"><span class="toc-text">手动应答方法及参数解释</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E6%81%AF%E8%87%AA%E5%8A%A8%E9%87%8D%E6%96%B0%E5%85%A5%E9%98%9F"><span class="toc-text">消息自动重新入队</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%8B%E5%8A%A8%E5%BA%94%E7%AD%94%E6%A1%88%E4%BE%8B"><span class="toc-text">手动应答案例</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-1"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%85-1"><span class="toc-text">消费者</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RabbitMQ%E6%8C%81%E4%B9%85%E5%8C%96"><span class="toc-text">RabbitMQ持久化</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%98%9F%E5%88%97%E6%8C%81%E4%B9%85%E5%8C%96%E5%92%8C%E6%B6%88%E6%81%AF%E6%8C%81%E4%B9%85%E5%8C%96%E8%A7%A3%E9%87%8A"><span class="toc-text">队列持久化和消息持久化解释</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%98%9F%E5%88%97%E6%8C%81%E4%B9%85%E5%8C%96"><span class="toc-text">队列持久化</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-2"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%85-2"><span class="toc-text">消费者</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E6%81%AF%E6%8C%81%E4%B9%85%E5%8C%96"><span class="toc-text">消息持久化</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-3"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%85-3"><span class="toc-text">消费者</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%8D%E5%85%AC%E5%B9%B3%E5%88%86%E5%8F%91"><span class="toc-text">不公平分发</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-4"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%85-4"><span class="toc-text">消费者</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%851"><span class="toc-text">消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%852"><span class="toc-text">消费者2</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%95%88%E6%9E%9C"><span class="toc-text">效果</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A2%84%E5%8F%96%E5%80%BC%E5%88%86%E5%8F%91"><span class="toc-text">预取值分发</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%91%E5%B8%83%E7%A1%AE%E8%AE%A4"><span class="toc-text">发布确认</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%91%E5%B8%83%E7%A1%AE%E8%AE%A4%E9%80%BB%E8%BE%91"><span class="toc-text">发布确认逻辑</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%80%E5%90%AF%E5%8F%91%E5%B8%83%E7%A1%AE%E8%AE%A4%E6%96%B9%E6%B3%95"><span class="toc-text">开启发布确认方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%95%E4%B8%AA%E7%A1%AE%E8%AE%A4%E5%8F%91%E5%B8%83"><span class="toc-text">单个确认发布</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%B9%E9%87%8F%E7%A1%AE%E8%AE%A4%E5%8F%91%E5%B8%83"><span class="toc-text">批量确认发布</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E7%A1%AE%E8%AE%A4"><span class="toc-text">异步确认</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%89%E7%A7%8D%E5%8F%91%E5%B8%83%E7%A1%AE%E8%AE%A4%E6%96%B9%E5%BC%8F%E5%AF%B9%E6%AF%94"><span class="toc-text">三种发布确认方式对比</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B6%88%E6%81%AF%E5%BA%94%E7%AD%94%E5%92%8C%E5%8F%91%E5%B8%83%E7%A1%AE%E8%AE%A4%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">消息应答和发布确认的区别</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%A4%E6%8D%A2%E6%9C%BA"><span class="toc-text">交换机</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%A4%E6%8D%A2%E6%9C%BA%EF%BC%88Exchanges%EF%BC%89"><span class="toc-text">交换机（Exchanges）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%A4%E6%8D%A2%E6%9C%BA%E7%B1%BB%E5%9E%8B"><span class="toc-text">交换机类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%B4%E6%97%B6%E9%98%9F%E5%88%97"><span class="toc-text">临时队列</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%91%E5%AE%9A%E4%BA%A4%E6%8D%A2%E6%9C%BA%EF%BC%88%E7%BB%91%E5%AE%9Abindings%EF%BC%89"><span class="toc-text">绑定交换机（绑定bindings）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%84%E7%B1%BB%E5%9E%8B%E4%BA%A4%E6%8D%A2%E6%9C%BA%E4%BD%BF%E7%94%A8"><span class="toc-text">各类型交换机使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Fanout"><span class="toc-text">Fanout</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-5"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%85-5"><span class="toc-text">消费者</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Direct"><span class="toc-text">Direct</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Direct%E4%BB%8B%E7%BB%8D"><span class="toc-text">Direct介绍</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A4%9A%E9%87%8D%E7%BB%91%E5%AE%9A"><span class="toc-text">多重绑定</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-6"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%851-1"><span class="toc-text">消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%852-1"><span class="toc-text">消费者2</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%93%E6%9E%9C"><span class="toc-text">结果</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Topics"><span class="toc-text">Topics</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Topic%E7%9A%84%E4%BB%8B%E7%BB%8D"><span class="toc-text">Topic的介绍</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Topic%E5%8C%B9%E9%85%8D%E6%A1%88%E4%BE%8B"><span class="toc-text">Topic匹配案例</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-7"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%851-2"><span class="toc-text">消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%852-2"><span class="toc-text">消费者2</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%93%E6%9E%9C-1"><span class="toc-text">结果</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%AD%BB%E4%BF%A1%E9%98%9F%E5%88%97"><span class="toc-text">死信队列</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%BB%E4%BF%A1%E6%A6%82%E5%BF%B5"><span class="toc-text">死信概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%BB%E4%BF%A1%E7%9A%84%E6%9D%A5%E6%BA%90"><span class="toc-text">死信的来源</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%BB%E4%BF%A1%E5%AE%9E%E6%88%98"><span class="toc-text">死信实战</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E6%81%AFTTL%E8%BF%87%E6%9C%9F"><span class="toc-text">消息TTL过期</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%AD%BB%E4%BF%A1%E6%9C%80%E5%A4%A7%E9%95%BF%E5%BA%A6"><span class="toc-text">死信最大长度</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%AD%BB%E4%BF%A1%E6%B6%88%E6%81%AF%E8%A2%AB%E6%8B%92"><span class="toc-text">死信消息被拒</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97"><span class="toc-text">延迟队列</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97%E4%BB%8B%E7%BB%8D"><span class="toc-text">延迟队列介绍</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#TTL%E7%9A%84%E4%B8%A4%E7%A7%8D%E8%AE%BE%E7%BD%AE"><span class="toc-text">TTL的两种设置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#SpringBoot%E4%B8%AD%E6%95%B4%E5%90%88RabbitMQ"><span class="toc-text">SpringBoot中整合RabbitMQ</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96"><span class="toc-text">依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#yml%E9%85%8D%E7%BD%AE"><span class="toc-text">yml配置</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%98%9F%E5%88%97TTL%E2%80%94SpringBoot"><span class="toc-text">队列TTL—SpringBoot</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E6%9E%B6%E6%9E%84%E5%9B%BE"><span class="toc-text">代码架构图</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#TTL%E9%85%8D%E7%BD%AE"><span class="toc-text">TTL配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-8"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%8B%E8%AF%95"><span class="toc-text">测试</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BB%B6%E6%97%B6%E9%98%9F%E5%88%97TTL%E4%BC%98%E5%8C%96"><span class="toc-text">延时队列TTL优化</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE%E7%B1%BB%E4%BB%A3%E7%A0%81"><span class="toc-text">配置类代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-9"><span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%8B%E8%AF%95-1"><span class="toc-text">测试</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Rabbitmq%E6%8F%92%E4%BB%B6%E5%AE%9E%E7%8E%B0%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97%EF%BC%88%E5%90%8E%E7%BB%AD%E8%A1%A5%E5%85%85%E6%88%96%E4%BF%AE%E6%94%B9%EF%BC%89"><span class="toc-text">Rabbitmq插件实现延迟队列（后续补充或修改）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8F%92%E4%BB%B6%E5%AE%9E%E6%88%98"><span class="toc-text">插件实战</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE%E7%B1%BB%E4%BB%A3%E7%A0%81-1"><span class="toc-text">配置类代码</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%91%E5%B8%83%E7%A1%AE%E8%AE%A4%E9%AB%98%E7%BA%A7"><span class="toc-text">发布确认高级</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%91%E5%B8%83%E7%A1%AE%E8%AE%A4SpringBoot%E7%89%88%E6%9C%AC"><span class="toc-text">发布确认SpringBoot版本</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D"><span class="toc-text">介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9E%E6%88%98"><span class="toc-text">实战</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0%E9%85%8D%E7%BD%AE%E7%B1%BB"><span class="toc-text">添加配置类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E6%81%AF%E7%94%9F%E4%BA%A7%E8%80%85"><span class="toc-text">消息生产者</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E6%81%AF%E6%B6%88%E8%B4%B9%E8%80%85"><span class="toc-text">消息消费者</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E6%81%AF%E7%94%9F%E4%BA%A7%E8%80%85%E5%8F%91%E5%B8%83%E6%B6%88%E6%81%AF%E5%90%8E%E7%9A%84%E5%9B%9E%E8%B0%83%E6%8E%A5%E5%8F%A3"><span class="toc-text">消息生产者发布消息后的回调接口</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9E%E9%80%80%E6%B6%88%E6%81%AF"><span class="toc-text">回退消息</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D-1"><span class="toc-text">介绍</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E6%88%98-1"><span class="toc-text">实战</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BF%AE%E6%94%B9%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-text">修改配置文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BF%AE%E6%94%B9%E5%9B%9E%E8%B0%83%E6%8E%A5%E5%8F%A3"><span class="toc-text">修改回调接口</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%87%E4%BB%BD%E4%BA%A4%E6%8D%A2%E6%9C%BA"><span class="toc-text">备份交换机</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D-2"><span class="toc-text">介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9E%E6%88%98-2"><span class="toc-text">实战</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BF%AE%E6%94%B9%E9%AB%98%E7%BA%A7%E7%A1%AE%E8%AE%A4%E5%8F%91%E5%B8%83-%E9%85%8D%E7%BD%AE%E7%B1%BB"><span class="toc-text">修改高级确认发布 配置类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8A%A5%E8%AD%A6%E6%B6%88%E8%B4%B9%E8%80%85"><span class="toc-text">报警消费者</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#RabbitMQ%E5%85%B6%E4%BB%96%E7%9F%A5%E8%AF%86%E7%82%B9"><span class="toc-text">RabbitMQ其他知识点</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B9%82%E7%AD%89%E6%80%A7"><span class="toc-text">幂等性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A6%82%E5%BF%B5-1"><span class="toc-text">概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E6%81%AF%E9%87%8D%E5%A4%8D%E6%B6%88%E8%B4%B9"><span class="toc-text">消息重复消费</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E6%80%9D%E8%B7%AF"><span class="toc-text">解决思路</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E7%AB%AF%E7%9A%84%E5%B9%82%E7%AD%89%E6%80%A7%E4%BF%9D%E9%9A%9C"><span class="toc-text">消费端的幂等性保障</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BC%98%E5%85%88%E7%BA%A7%E9%98%9F%E5%88%97"><span class="toc-text">优先级队列</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-text">使用场景</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0%E6%96%B9%E6%B3%95"><span class="toc-text">添加方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E6%88%98-3"><span class="toc-text">实战</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85%E4%BB%A3%E7%A0%81"><span class="toc-text">生产者代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%85%E4%BB%A3%E7%A0%81"><span class="toc-text">消费者代码</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%83%B0%E6%80%A7%E9%98%9F%E5%88%97"><span class="toc-text">惰性队列</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF-1"><span class="toc-text">使用场景</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%A4%E7%A7%8D%E6%A8%A1%E5%BC%8F"><span class="toc-text">两种模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E5%BC%80%E9%94%80%E5%AF%B9%E6%AF%94"><span class="toc-text">内存开销对比</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-color: transparent;"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">格言🧬</p><div class="bg-ad"><div>再看看那个光点，它就在这里，这是家园，这是我们 —— 你所爱的每一个人，你认识的一个人，你听说过的每一个人，曾经有过的每一个人，都在它上面度过他们的一生✨</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://stellarium.org/">点击开启星辰之旅</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">猜你想看💡</p><ul class="ft-links"><li><a href="/posts/eec9786.html">魔改指南</a><a href="/box/nav/">网址导航</a></li><li><a href="/social/link/">我的朋友</a><a href="/comments/">留点什么</a></li><li><a href="/personal/about/">关于作者</a><a href="/archives/">文章归档</a></li><li><a href="/categories/">文章分类</a><a href="/tags/">文章标签</a></li><li><a href="/box/Gallery/">我的画廊</a><a href="/personal/bb/">我的唠叨</a></li><li><a href="/site/time/">建设进程</a><a href="/site/census/">网站统计</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链⌛</p><div class="ft-img-group"><div class="img-group-item"><a href="https://www.naste.top:1024/" title="XiaoFei🥝"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div></div></div></div><div class="copyright"><span><b>&copy;2022-2024</b></span><span><b>&nbsp;&nbsp;By XiaoFei🥝</b></span></div><div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" title="博客框架为Hexo_v6.3.0"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Frame-Hexo-blue.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" title="主题版本Butterfly_v4.3.1"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Theme-Butterfly-6513df.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://vercel.com/" style="margin-inline:5px" title="本站采用多线部署，主线路托管于Vercel"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Hosted-Vercel-brightgreen.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://user.51.la/" style="margin-inline:5px" title="本站数据分析得益于51la技术支持"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Analytics-51la-3db1eb.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" style="margin-inline:5px" title="本网站源码由Github提供存储仓库"><img src= "" data-lazy-src=" https://static.naste.top:1024/svg/blog/Source-Github-d021d6.svg" alt=""/></a></p></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><a class="icon-V hidden" onclick="switchNightMode()" title="浅色和深色模式转换"><svg width="25" height="25" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon"></use></svg></a><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button><button class="share" type="button" title="右键模式" onclick="changeMouseMode()"><i class="fas fa-mouse"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog right_side"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button class="share" type="button" title="分享链接" onclick="share()"><i class="fas fa-share-nodes"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i><span id="percent">0<span>%</span></span></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div class="js-pjax" id="rightMenu"><div class="rightMenu-group rightMenu-small"><a class="rightMenu-item" href="javascript:window.history.back();"><i class="fa fa-arrow-left"></i></a><a class="rightMenu-item" href="javascript:window.history.forward();"><i class="fa fa-arrow-right"></i></a><a class="rightMenu-item" href="javascript:window.location.reload();"><i class="fa fa-refresh"></i></a><a class="rightMenu-item" href="javascript:rmf.scrollToTop();"><i class="fa fa-arrow-up"></i></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-text"><a class="rightMenu-item" href="javascript:rmf.copySelect();"><i class="fa fa-copy"></i><span>复制</span></a><a class="rightMenu-item" href="javascript:window.open(&quot;https://www.baidu.com/s?wd=&quot;+window.getSelection().toString());window.location.reload();"><i class="fa fa-search"></i><span>百度搜索</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-too"><a class="rightMenu-item" href="javascript:window.open(window.getSelection().toString());window.location.reload();"><i class="fa fa-link"></i><span>转到链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-paste"><a class="rightMenu-item" href="javascript:rmf.paste()"><i class="fa fa-copy"></i><span>粘贴</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-post"><a class="rightMenu-item" href="#post-comment"><i class="fas fa-comment"></i><span>空降评论</span></a><a class="rightMenu-item" href="javascript:rmf.copyWordsLink()"><i class="fa fa-link"></i><span>复制本文地址</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-to"><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>新窗口打开</span></a><a class="rightMenu-item" id="menu-too" href="javascript:rmf.open()"><i class="fa fa-link"></i><span>转到链接</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-img"><a class="rightMenu-item" href="javascript:rmf.saveAs()"><i class="fa fa-download"></i><span>保存图片</span></a><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>在新窗口打开</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制图片链接</span></a></div><div class="rightMenu-group rightMenu-line"><a class="rightMenu-item" href="javascript:randomPost()"><i class="fa fa-paper-plane"></i><span>随便逛逛</span></a><a class="rightMenu-item" href="javascript:switchNightMode();"><i class="fa fa-moon"></i><span>昼夜切换</span></a><a class="rightMenu-item" href="/personal/about/"><i class="fa fa-info-circle"></i><span>关于博客</span></a><a class="rightMenu-item" href="javascript:toggleWinbox();"><i class="fas fa-cog"></i><span>美化设置</span></a><a class="rightMenu-item" href="javascript:rmf.fullScreen();"><i class="fas fa-expand"></i><span>切换全屏</span></a><a class="rightMenu-item" href="javascript:window.print();"><i class="fa-solid fa-print"></i><span>打印页面</span></a></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.umd.min.js"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/instant.page/5.1.0/instantpage.min.js" type="module"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vanilla-lazyload/17.3.1/lazyload.iife.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdnjs.cloudflare.com/ajax/libs/pangu/4.0.7/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (true){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())
setTimeout(function(){preloader.endLoading();}, 5000);
document.getElementById('loading-box').addEventListener('click',()=> {preloader.endLoading()})</script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.min.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: '',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: '',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.staticfile.org/twikoo/1.6.8/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script src="https://cdn.staticfile.org/jquery/3.6.3/jquery.min.js"></script><script async src="https://cdn1.tianli0.top/npm/vue@2.6.14/dist/vue.min.js"></script><script async src="https://cdn1.tianli0.top/npm/element-ui@2.15.6/lib/index.js"></script><script async src="https://cdn.bootcdn.net/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script><script defer type="text/javascript" src="https://cdn1.tianli0.top/npm/sweetalert2@8.19.0/dist/sweetalert2.all.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer src="https://cdn1.tianli0.top/gh/nextapps-de/winbox/dist/winbox.bundle.min.js"></script><script async src="//at.alicdn.com/t/c/font_3586335_hsivh70x0fm.js"></script><script async src="//at.alicdn.com/t/c/font_3636804_gr02jmjr3y9.js"></script><script async src="//at.alicdn.com/t/c/font_3612150_kfv55xn3u2g.js"></script><script async src="https://cdn.wpon.cn/2022-sucai/Gold-ingot.js"></script><canvas id="universe"></canvas><canvas id="snow"></canvas><script defer src="/js/fomal.js"></script><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.js"></script><script src="https://cdn1.tianli0.top/npm/js-heo@1.0.12/metingjs/Meting.min.js"></script><script src="https://lib.baomitu.com/pjax/0.2.8/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show","#web_bg",".js-pjax","#bibi","body > title","#app","#tag-echarts","#posts-echart","#categories-echarts"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --> <script data-pjax>if(document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    var parent = document.getElementById('recent-posts');
    var child = '<div class="recent-post-item" style="width:100%;height: auto"><div id="catalog_magnet"><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Java/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍡 XiaoFeiのJava学习笔记 (55)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Linux/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍼 XiaoFeiのLinux笔记 (33)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Python/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍉 XiaoFeiのPython笔记 (2)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/前端/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍟 XiaoFeiの前端笔记 (17)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Other/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍥 XiaoFeiのOther笔记 (10)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item" style="visibility: hidden"></div><a class="magnet_link_more"  href="https://www.naste.top:1024/categories/" style="flex:1;text-align: center;margin-bottom: 10px;">查看更多...</a></div></div>';
    console.log('已挂载magnet')
    parent.insertAdjacentHTML("afterbegin",child)}
     </script><style>#catalog_magnet{flex-wrap: wrap;display: flex;width:100%;justify-content:space-between;padding: 10px 10px 0 10px;align-content: flex-start;}.magnet_item{flex-basis: calc(33.333333333333336% - 5px);background: #e9e9e9;margin-bottom: 10px;border-radius: 8px;transition: all 0.2s ease-in-out;}.magnet_item:hover{background: var(--text-bg-hover)}.magnet_link_more{color:#555}.magnet_link{color:black}.magnet_link:hover{color:white}@media screen and (max-width: 600px) {.magnet_item {flex-basis: 100%;}}.magnet_link_context{display:flex;padding: 10px;font-size:16px;transition: all 0.2s ease-in-out;}.magnet_link_context:hover{padding: 10px 20px;}</style>
    <style></style><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912191.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-08</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</a><div class="blog-slider__text">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678672933.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-15</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">Hexo中Markdown语法与外挂标签写法汇总</a><div class="blog-slider__text">Hexo中Markdown语法与外挂标签写法汇总</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper_init.js"></script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script></div><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js"></script><script data-pjax src="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.js"></script><script data-pjax>
  function gitcalendar_injector_config(){
      var parent_div_git = document.getElementById('gitZone');
      var item_html = '<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 320px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>';
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      console.log('已挂载gitcalendar')
      }

    if( document.getElementById('gitZone') && (location.pathname ==='/personal/about/'|| '/personal/about/' ==='all')){
        gitcalendar_injector_config()
        GitCalendarInit("https://gitcalendar.naste.top/api?xiao-i-fei",['#d9e0df', '#c6e0dc', '#a8dcd4', '#9adcd2', '#89ded1', '#77e0d0', '#5fdecb', '#47dcc6', '#39dcc3', '#1fdabe', '#00dab9'],'xiao-i-fei')
    }
  </script><!-- hexo injector body_end end --></body></html>